package com;

import com.conn.ConnectionUtil;
import com.entity.ProductCodeEntity;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.JDBCType;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

public class ProductCode {

    private Map<String, String> columns = new HashMap<String, String>();
    private Map<String, String> columnsType = new HashMap<String, String>();
    private Map<String, String> columnsComment = new HashMap<String, String>();

    private Map<String, String> getMethodNameMap = new HashMap<String, String>();
    private Map<String, String> setMethodNameMap = new HashMap<String, String>();
    private Map<String, Integer> filedLength = new HashMap<String, Integer>();
    private Map<String, String> filedType = new HashMap<String, String>();
    private Map<String, String> filedComment = new HashMap<String, String>();


    private List<String> fileds = new LinkedList<String>();

    private String[] nums = {"java.lang.Integer", "java.lang.Long", "java.lang.Double", "java.lang.Float"};

    private String[] intType = {"smallint", "int", "TINYINT", "tinyint"};
    private String[] dateType = {"datetime", "TIMESTAMP"};
    private String[] booleanType = {"bit"};
    private String[] LongType = {"BIGINT"};
    private String[] bigdecType = {"numeric", "decimal"};
    private String[] LocalDateType = {"date"};


    private String entityName = "";
    private String primaryKeyStr = "";

    private String dtoName = null;
    private String mapperName = null;
    private String serviceName = null;
    private String adminServiceName = null;
    private String managerSevice = null;
    private String resultName = null;
    private String requestName = null;
    private String repositoryName = null;
    private String voName = null;
    private String feignApi = null;

    private String idColumn = "";
    private String idFiled = "";
    private String idColumnDbType = "";
    private String IdFiledType = "";

    private String dtoImpl = "";
    private String entityImpl = "";
    private String voImpl = "";
    private String serviceImpl = "";
    private String mapperImpl = "";
    private String pageResultVOImpl = "";
    private String responseDataImpl = "";
    private String constant = "";
    private String responseDateMethod = "";
    private String queryDTO = "";
    private String addDTO = "";
    private String updateDTO = "";
    private String updateStatusDTO = "";


    private ProductCodeEntity entity = null;
    private Boolean statucFlag = Boolean.FALSE;
    private List<String> booleanFiled = new ArrayList<>();

    private final static String BASE_PATH = "D:\\temp software\\productCode";
    private static boolean is_open = Boolean.FALSE;


    public void choose(ProductCodeEntity entity)
            throws IOException {
        String className = format(entity.getTable(), entity.getBeforeCharacter(), entity.getStartCharacter());
        dtoName = className + "DTO";
        updateDTO = className + "OfUpdateDTO";
        updateStatusDTO = className + "OfUpdateStatusDTO";
        addDTO = className + "OfAddDTO";
        queryDTO = className + "OfQueryDTO";

        mapperName = className + "Mapper";
        serviceName = className + entity.getServiceNameOfAfter();
        adminServiceName = className + entity.getServiceNameOfAfter() + "Admin";
        managerSevice = className + "Manager";
        resultName = className + "PageResult";
        requestName = className + "Request";
        repositoryName = className + "Repository";
        voName = className + "VO";

        if (StringUtils.isEmpty(entity.getBasePath())) {
            entity.setBasePath(BASE_PATH + "/" + UUID.randomUUID());
            is_open = Boolean.TRUE;
        }

        this.entity = entity;

        this.pageResultVOImpl = entity.getPageResultVOImpl();
        this.responseDataImpl = entity.getResponseDataImpl();
        this.constant = entity.getConstant();
        this.responseDateMethod = entity.getResponseDateMethod();

        primaryKeyStr = getPrimaryKeyColumns(entity.getTable(), entity.getDbName(), entity.getIp(), entity.getUser(), entity.getPwd());
        if (StringUtils.isEmpty(primaryKeyStr)) {
            primaryKeyStr = "id";
        }
//        String path = "d:/temp software/productCode/" + UUID.randomUUID() + "/";
        List<Map<String, String>> data = getColumnsData(entity.getTable(), entity.getDbName(), entity.getIp(), entity.getUser(), entity.getPwd());
        if (Objects.isNull(data) || data.size() == 0) {
            throw new RuntimeException("【" + entity.getTable() + "】表名错误;查不到对应的列");
        }


        chooseEntity(data, entity.getTable(), className, getPath(entity.getBasePath(), entity.getEntityStr()), getPackageStr(entity.getEntityStr()));
        entityImpl = getPackageStr(entity.getEntityStr()) + "." + entityName;
        mapperImpl = getPackageStr(entity.getMapperStr()) + "." + mapperName;

//		chooseMapper(path, className);
        chooseMapperXML(getPath(entity.getBasePath(), entity.getMapperXMLPath()), className, entity.getTable(), entityImpl, mapperImpl);

        chooseEntityVO(className, getPath(entity.getBasePath(), entity.getVoStr()), getPackageStr(entity.getVoStr()), entityImpl);


        chooseUpdateQueryDto(queryDTO, getPath(entity.getBasePath(), entity.getDtoStr()), getPackageStr(entity.getDtoStr()), entityImpl);

        chooseOperator();
        chooseEntityDto(addDTO, getPath(entity.getBasePath(), entity.getDtoStr()), getPackageStr(entity.getDtoStr()), entityImpl, Boolean.TRUE);
        chooseEntityDto(updateDTO, getPath(entity.getBasePath(), entity.getDtoStr()), getPackageStr(entity.getDtoStr()), entityImpl, Boolean.TRUE);
        chooseUpdateStatusDto(updateStatusDTO, getPath(entity.getBasePath(), entity.getDtoStr()), getPackageStr(entity.getDtoStr()), entityImpl);

        dtoImpl = getPackageStr(entity.getDtoStr()) + "." + dtoName;
        voImpl = getPackageStr(entity.getVoStr()) + "." + voName;

        chooseMapper(className, getPath(entity.getBasePath(), entity.getMapperStr()), mapperName, getPackageStr(entity.getMapperStr()), entityImpl);
        chooseService(getPath(entity.getBasePath(), entity.getServiceStr()), className, getPackageStr(entity.getServiceStr()), entityImpl);

        serviceImpl = getPackageStr(entity.getServiceStr()) + "." + serviceName;

        chooseServiceImpl(getPath(entity.getBasePath(), entity.getServiceImplStr()), serviceImpl, getPackageStr(entity.getServiceImplStr()), entityImpl, mapperImpl);

//        chooseRepository(path);
//        chooseRequest(path);
//        choosePageResult(path);
        chooseController(getPath(entity.getBasePath(), entity.getControllerStr()), className, serviceImpl, voImpl, dtoImpl, entityImpl, entity.getTable(), getPackageStr(entity.getControllerStr()));
//        chooseManagerSevice(path);
//        chooseManagerServiceImpl(path, className);
//        chooseAdminController(path, className);
//        chooseAdminListJsp(path, className);
//        chooseAdminAddJsp(path, className);
//        chooseAdminEditJsp(path, className);
//        chooseAdminListJs(path, className);
//        chooseAdminAddAndEditJs(path, className);
//        chooseAdminService(path, className);
//        chooseAdminServiceImpl(path);
//        chooseAdminServiceTest(path, className);
//        chooseManagerAdminServiceImpl(path, className);
//        chooseServiceTest(path, className);
//        writeDubbo(path);
//        chooseAdminListJspOfLayout(path, className);
//        chooseAdminEditLayUi(path, className);

        chooseFeign(getPath(entity.getBasePath(), entity.getFeignStr()), getPackageStr(entity.getFeignStr()), className, entity.getFeignService(), entity.getTable());

        if (is_open) {
            Desktop.getDesktop().open(new File(entity.getBasePath()));
        }

        System.out.println(entity.getBasePath());
    }

    private String getPath(String batchPath, String str) {
        StringBuilder builder = new StringBuilder();
        builder.append(batchPath);

        if (StringUtils.isNotEmpty(str)) {
            builder.append("/");
            str = StringUtils.replace(str, ".", "/");
            str = StringUtils.replace(str, ";", "/");
            builder.append(str);
        }
        return builder.toString();
    }

    private String getPackageStr(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }

        if (StringUtils.indexOf(str, ";") > 0) {
            return StringUtils.substringAfter(str, ";");
        }

        return null;
    }

    private void writeDubbo(String path) throws IOException {
        String filedServiceName = formatFiledClass(serviceName);
        List<String> lines = new ArrayList<String>();
        lines.add(" <dubbo:reference id=\"" + filedServiceName + "\" interface=\"\" version=\"1.0.0\"/>");
        write(lines, path + "admin/", "dubbo.txt");
    }

    private void chooseServiceTest(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "ServiceImplTest";
        String service = formatFiledClass(serviceName);

        lines.add("import org.junit.Test;");
        lines.add("import org.junit.runner.RunWith;");
        lines.add("import org.slf4j.Logger;");
        lines.add("import org.slf4j.LoggerFactory;");
        lines.add("import org.springframework.boot.test.context.SpringBootTest;");
        lines.add("import org.springframework.test.context.junit4.SpringRunner;");
        lines.add("import org.springframework.beans.factory.annotation.Autowired;");

        lines.add("@SpringBootTest");
        lines.add("@RunWith(SpringRunner.class)");
        lines.add("public class " + name + " {");
        lines.add("private final static Logger LOGGER = LoggerFactory.getLogger(" + name + ".class);");
        lines.add("@Autowired");
        lines.add("private " + adminServiceName + " " + service + ";");

        lines.add("@Test");
        lines.add("public void testSelectLimitPage() {");
        lines.add("try{");
        lines.add(requestName + " request = new " + requestName + "();");
        lines.add(resultName + " result = " + service + ".selectLimitPage(request);");
        lines.add(" LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");
        lines.add("@Test");
        lines.add("public void testSelectById() {");
        lines.add("try{");
        lines.add(requestName + " request = new " + requestName + "();");
        lines.add("SimpleResult<" + dtoName + "> result = " + service + ".selectById(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");

        lines.add("@Test");
        lines.add("public void testInsert() {");
        lines.add("try{");
        lines.addAll(chooseServiceTestNewObj());
        lines.add("BaseResult result = " + service + ".insert(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");

        lines.add("@Test");
        lines.add("public void testUpdate() {");
        lines.add("try{");
        lines.addAll(chooseServiceTestNewObj());
        lines.add("BaseResult result = " + service + ".update(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");
        lines.add("}");

        write(lines, path + "service/", name + ".java");
    }

    private void chooseAdminServiceTest(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "AdminServiceImplTest";
        String service = formatFiledClass(serviceName);

        lines.add("import org.junit.Test;");
        lines.add("import org.junit.runner.RunWith;");
        lines.add("import org.slf4j.Logger;");
        lines.add("import org.slf4j.LoggerFactory;");
        lines.add("import org.springframework.boot.test.context.SpringBootTest;");
        lines.add("import org.springframework.test.context.junit4.SpringRunner;");
        lines.add("import org.springframework.beans.factory.annotation.Autowired;");

        lines.add("@SpringBootTest");
        lines.add("@RunWith(SpringRunner.class)");
        lines.add("public class " + name + " {");
        lines.add("private final static Logger LOGGER = LoggerFactory.getLogger(" + name + ".class);");
        lines.add("@Autowired");
        lines.add("private " + adminServiceName + " " + service + ";");

        lines.add("@Test");
        lines.add("public void testSelectLimitPage() {");
        lines.add("try{");
        lines.add(requestName + " request = new " + requestName + "();");
        lines.add(resultName + " result = " + service + ".selectLimitPage(request);");
        lines.add(" LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");
        lines.add("@Test");
        lines.add("public void testSelectById() {");
        lines.add("try{");
        lines.add(requestName + " request = new " + requestName + "();");
        lines.add("SimpleResult<" + dtoName + "> result = " + service + ".selectById(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");

        lines.add("@Test");
        lines.add("public void testInsert() {");
        lines.add("try{");
        lines.addAll(chooseServiceTestNewObj());
        lines.add("BaseResult result = " + service + ".insert(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");

        lines.add("@Test");
        lines.add("public void testUpdate() {");
        lines.add("try{");
        lines.addAll(chooseServiceTestNewObj());
        lines.add("BaseResult result = " + service + ".update(request);");
        lines.add("LOGGER.info(\"{}\",result);");
        lines.add("} catch (Exception e) {");
        lines.add("LOGGER.error(e.getMessage(),e);");
        lines.add("throw new RuntimeException(e);");
        lines.add("}");
        lines.add("}");
        lines.add("}");

        write(lines, path + "service/", name + ".java");
    }

    private List<String> chooseServiceTestNewObj() {
        List<String> lines = new ArrayList<String>();
        lines.add(requestName + " request = new " + requestName + "();");
        fileds.forEach((filed) -> {
            String setName = setMethodNameMap.get(filed);
            String type = filedType.get(filed);
            if ("java.lang.String".equals(type)) {
                lines.add("request." + setName + "(\"\");");
            } else if ("java.time.LocalDateTime".equals(type)) {

                lines.add("request." + setName + "(java.time.LocalDateTime.now());");
            } else {
                lines.add("request." + setName + "();");
            }

        });
        return lines;
    }

    private void chooseAdminAddAndEditJs(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "AddAndEdit";
        lines.add("mini.parse();");
        lines.add("var form = new mini.Form(\"form1\");");
        lines.add("$(\"#taskTypeDate\").hide();");
        lines.add("function onsave(url) { SaveData(url);}");
//		lines.add("function onEdit(e) { SaveData('');}");
        lines.add("function SaveData(url) {");
        lines.add("  var o = form.getData();");
        lines.add("  form.validate();");
        lines.add("  if (form.isValid() == false){return;}");
        lines.add("  $.ajax({url:url,type: 'post', data: o, cache: false,");
        lines.add(
                "     success: function (result) { if(result.success == true){ CloseWindow(\"save\"); window.parent.refreshTabByName(mini.get(\"tabName\").getValue());  }else{ showTips(result.errorMessage);}},");
        lines.add("     error: function (jqXHR, textStatus, errorThrown) { showTips(\"网络错误，请稍后再试！\"); }  });");
        lines.add("}");
        lines.add(
                "function CloseWindow(action) {if(action == \"close\" && form.isChanged()){mini.confirm(\"数据被修改了，是否先保存？\", \"确定？\", function(action) {if (action == \"ok\") {return false;}});} if (window.CloseOwnerWindow){return window.CloseOwnerWindow(action);}else{window.close();}}");
        lines.add("function onCancel(e) {CloseWindow(\"cancel\");}");
        write(lines, path + "admin/", name + ".js");
    }

    private void chooseAdminListJs(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "List";
        lines.add("mini.parse();");
        lines.add("var baseURL =ctx+'';");
        lines.add("var grid = mini.get(\"grid\");");
        lines.add("grid.setUrl(baseURL + \"/getDataList\");");
        lines.add("search();");
        lines.add("function search() {");
        lines.add("  //var taskName = mini.get(\"taskName\").getValue();");
        lines.add("  var params = {};");
        lines.add(" // params[\"taskName\"] = taskName;");
        lines.add(" grid.load(params);");
        lines.add("}");
        lines.add("//增加");
        lines.add("function add(){");
        lines.add("//	var tab = window.parent.getCurrentTab();var tabName = tab.name;var params = {};");
        lines.add("// params[\"id\"] = \"add_" + className + "_windows\";");
        lines.add("// params[\"text\"] = \"增加\";");
        lines.add("// params[\"url\"] = \"//toAdd?tabName=\" + tabName;");
        lines.add("// window.parent.showTab(params);");
        lines.add(" open_window(ctx + \"/toAdd\",\"新增\");");
        lines.add("");
//		lines.add(" mini.open({");
//		lines.add("   url: ctx + \"/toAdd\",");
//		lines.add("   title: \"增加\", width: 450, height: 450,");
//		lines.add("   onload: function () { var iframe = this.getIFrameEl(); iframe.focus(); },");
//		lines.add("   ondestroy: function (action) {if (action == \"save\") { showTips(\"添加成功！\");search();}}");
//		lines.add("   });");
        lines.add(" }");
        lines.add("function open_window(url,title){");
        lines.add(" mini.open({");
        lines.add("   url: url,title: title, width: 450, height: 450,");
        lines.add("   onload: function () { var iframe = this.getIFrameEl(); iframe.focus(); },");
        lines.add("   ondestroy: function (action) {if (action == \"save\") { showTips(\"添加成功！\");search();}}");
        lines.add("   });");
        lines.add("}");
        lines.add("");
        lines.add("");
        lines.add("}");
        lines.add("//修改");
        lines.add("function edit() {");
        lines.add(" // var rows = grid.getSelecteds();");
        lines.add(
                " // if(rows.length < 1){showTips(\"请选中一条记录\");return;}else if(rows.length > 1){showTips(\"只能选中一条记录\");return;}");
        lines.add(" // var tab = window.parent.getCurrentTab();var tabName = tab.name;var params = {};");
        lines.add(" // params[\"id\"] = \"edit_" + className + "_windows\" + rows[0].id;");
        lines.add(" // params[\"text\"] = \"修改\";");
        lines.add(" // params[\"url\"] = \"//toEdit/\" + rows[0].id + \"?tabName=\" + tabName;");
        lines.add(" // window.parent.showTab(params);");
        lines.add(" open_window(ctx + \"/toEdit\",\"修改\");");
        lines.add("}");
        lines.add("//删除");
        lines.add("function remove(){");
        lines.add("  var rows = grid.getSelecteds();");
        lines.add("  if (rows.length > 0) {");
        lines.add("    mini.confirm(\"确定要删除选中的数据吗？\",\"确定？\",function(action){");
        lines.add("      if(action == \"ok\"){var params = {};var ids = [];");
        lines.add("         for (var i=0, len=rows.length; i<len; i++) {ids.push(rows[i].id);}");
        lines.add("         params[\"ids\"] = ids;");
        lines.add("         grid.loading(\"操作中，请稍后......\");");
        lines.add("         var url = ctx + \"//deleteByIds\";");
        lines.add("         $.post(url, params, function(result){");
        lines.add(
                "           if(result.success == true){showTips(\"删除成功！\");delReset(grid, rows.length);grid.reload();grid.deselectAll(true);");
        lines.add(
                "           }else{showTips(result.errorMessage);}grid.unmask();});}});} else {showTips(\"请选中一条记录\");}}");

        write(lines, path + "admin/", name + ".js");
    }

    private void chooseAdminEditJsp(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "Edit";

        lines.add("<%@ page language=\"java\" contentType=\"text/html;charset=UTF-8\" pageEncoding=\"UTF-8\"%>");
        lines.add("<%@ include file=\"/views/include/taglib.jsp\"%>");
        lines.add("<%@ include file=\"/views/include/include.jsp\"%>");
        lines.add("<!DOCTYPE html>");
        lines.add("<html>");
        lines.add("<head>");
        lines.add("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />");
        lines.add("<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />");
        lines.add("<title>修改</title>");
        lines.add("</head>");
        lines.add("<body>");
        lines.add("	<form id=\"form1\" method=\"post\" class=\"form-horizontal\">");
        lines.add("	  <div style=\"padding-left:11px;padding-bottom:5px;\">");
        lines.add("     <input name=\"action\" class=\"mini-hidden\"/>");
        lines.add("     <input name=\"id\" class=\"mini-hidden\"/>");
        lines.add("     <table class=\"templeteTable2\" style=\"table-layout:fixed;\">");
        fileds.forEach((filed) -> {
            String commons = filedComment.get(filed);
            Integer length = filedLength.get(filed);
            lines.add("	   <tr></tr>");
            lines.add("    <tr>");
            lines.add("      <td>" + commons + "<span style=\"color: red;\">*</span>：</td>");
            lines.add("      <td>");
            String str = " <input name=\"" + filed + "\"  value=\"${vo." + filed
                    + "}\" class=\"mini-textbox w220\"  required=\"true\" ";
            if (null != length) {
                str = str + "vtype=\"rangeChar:0," + length + "\" maxErrorText='" + commons + "最大长度为" + length + "'";
            }
            str = str + "/>";
            lines.add("        " + str);
            lines.add("      </td>");
            lines.add("    </tr>");
        });
        lines.add("     </table>");
        lines.add(" <div style=\"text-align:left;padding:10px; margin-left: 250px;\">");
        lines.add("   <a id=\"_ok\" class=\"mini-button w60\" onclick=\"onsave('${ctxStatic}//${action}')\">确定</a>");
        lines.add("   <span style=\"display:inline-block;width:25px;\"></span>");
        lines.add("   <a id=\"_cancel\" class=\"mini-button w60\" onclick=\"onCancel\">关闭</a>");
        lines.add(" </div>");
        lines.add("</form>");
        lines.add("<script>");
        lines.add("document.write(\"<script type='text/javascript' src='${ctxStatic}/js//" + className
                + "AddAndEdit.js?v=\" + Date.now() + \"'><\\/script>\");");
        lines.add("</script>");
        lines.add("</body>");
        lines.add("</html>");

        write(lines, path + "admin/", name + ".jsp");
    }

    private void chooseAdminAddJsp(String path, String className) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = className + "Add";

        lines.add("<%@ page language=\"java\" contentType=\"text/html;charset=UTF-8\" pageEncoding=\"UTF-8\"%>");
        lines.add("<%@ include file=\"/views/include/taglib.jsp\"%>");
        lines.add("<%@ include file=\"/views/include/include.jsp\"%>");
        lines.add("<!DOCTYPE html>");
        lines.add("<html>");
        lines.add("<head>");
        lines.add("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />");
        lines.add("<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />");
        lines.add("<title>增加</title>");
        lines.add("</head>");
        lines.add("<body>");
        lines.add("	<form id=\"form1\" method=\"post\" class=\"form-horizontal\">");
        lines.add("	  <div style=\"padding-left:11px;padding-bottom:5px;\">");
        lines.add("     <input name=\"action\" class=\"mini-hidden\"/>");
        lines.add("     <input name=\"id\" class=\"mini-hidden\"/>");
        lines.add("     <table class=\"templeteTable2\" style=\"table-layout:fixed;\">");
        fileds.forEach((filed) -> {
            String commons = filedComment.get(filed);
            Integer length = filedLength.get(filed);
            lines.add("	    <tr></tr>");
            lines.add("     <tr>");
            lines.add("       <td>" + commons + "<span style=\"color: red;\">*</span>：</td>");
            lines.add("       <td>");
            lines.add("         <input name=\"" + filed + "\" class=\"mini-textbox w220\" vtype=\"rangeChar:0," + length
                    + "\" required=\"true\" requiredErrorText='" + commons + "不能为空'  maxErrorText='" + commons + "最大长度为"
                    + length + "'/>");
            lines.add("       </td>");
            lines.add("    </tr>");
        });
        lines.add("     </table>");
        lines.add(" <div style=\"text-align:left;padding:10px; margin-left: 250px;\">");
        lines.add("   <a id=\"_ok\" class=\"mini-button w60\" onclick=\"onOk\">确定</a>");
        lines.add("   <span style=\"display:inline-block;width:25px;\"></span>");
        lines.add("   <a id=\"_cancel\" class=\"mini-button w60\" onclick=\"onCancel\">关闭</a>");
        lines.add(" </div>");
        lines.add("</form>");
        lines.add("<script>");
        lines.add("document.write(\"<script type='text/javascript' src='${ctxStatic}/js//" + className
                + "AddAndEdit.js?v=\" + Date.now() + \"'><\\/script>\");");
        lines.add("</script>");
        lines.add("</body>");
        lines.add("</html>");

        write(lines, path + "admin/", name + ".jsp");
    }

    private void chooseAdminListJspOfLayout(String path, String className) throws IOException {
        List<String> lists = new ArrayList<String>();
        String name = className + "LayUiList";

        lists.add("<!DOCTYPE html>");
        lists.add("<html>");
        lists.add("<head>");
        lists.add("    <meta charset=\"UTF-8\">");
        lists.add("    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">");
        lists.add("    <link rel=\"stylesheet\" data-th-href=\"@{assets/css/layui.css}\">");
        lists.add("   <link rel=\"stylesheet\" data-th-href=\"@{assets/css/view.css}\"/>");
        lists.add("    <title></title>");
        lists.add("</head>");
        lists.add("<div data-th-include=\"common/common\"></div>");
        lists.add("<body class=\"layui-view-body\">");

        lists.add("<div class=\"layui-content\">");
        lists.add("   <div class=\"layui-row\">");
        lists.add("        <div class=\"layui-card\">");
        lists.add("            <div style=\"padding-top:10px;margin: 0 10px 0 10px\">");
        lists.add("                <form class=\"layui-form " + className + "-table-form\" action=\"\">");
        lists.add("                    <div class=\"row conditionTb\" >");

        fileds.forEach((filed) -> {
            String common = filedComment.get(filed);

            lists.add("                            <div class=\"layui-input-inline\">");

            lists.add("                                <input type=\"text\" class=\"layui-input form-control\" id=\""
                    + filed + "\" name=\"" + filed + "\" placeholder=\"" + common + "\"/>");
            lists.add("                            </div>");
        });
        lists.add(
                "                            <button type=\"button\" class=\"layui-btn layui-btn-blue\" onclick=\"search()\"> 查询</button>");
        lists.add(
                "                            <div class=\"actions__item zmdi zmdi-refresh-alt\" onclick=\"refresh()\" title=\"刷新\" ></div>");
        lists.add("                            <div class=\"dropdown actions__item\">");
        lists.add("                                <i data-toggle=\"dropdown\" class=\"zmdi zmdi-download\"> </i>");
        lists.add("                                <ul class=\"dropdown-menu dropdown-menu-right\">");

        lists.add(
                "                                    <a href=\"javascript:void(0)\" class=\"dropdown-item\" data-table-action=\"excel\" onclick=\"exportUserExcel()\"> Excel (.xlsx) </a>");
        lists.add(
                "                                    <a href=\"javascript:void(0)\" class=\"dropdown-item\" data-table-action=\"csv\" onclick=\"exportUserCsv()\"> CSV(.csv) </a>");
        lists.add("                                </ul>");
        lists.add("                            </div>");
        lists.add(
                "                            <div class=\"dropdown actions__item\" shiro:hasAnyPermissions=\"user:add,user:delete,user:update\">");
        lists.add("                                <i data-toggle=\"dropdown\" class=\"zmdi zmdi-more-vert\"></i>");
        lists.add(
                "                                    <a href=\"javascript:void(0)\" class=\"dropdown-item\" data-toggle=\"modal\" data-target=\"#user-add\" shiro:hasPermission=\":add\">新增</a>");
        lists.add(
                "                                    <a href=\"javascript:void(0)\" class=\"dropdown-item\" onclick=\"updateFunction()\" shiro:hasPermission=\":update\">修改</a>");
        lists.add(
                "                                    <a href=\"javascript:void(0)\" class=\"dropdown-item\" onclick=\"deleteFunction()\" shiro:hasPermission=\"user:delete\">删除</a>");
        lists.add("                                </div>");
        lists.add("                            </div>");

        lists.add("                        </div>");
        lists.add("                    </div>");
        lists.add("                </form>");
        lists.add("                <table id=\"" + className
                + "Table\" data-mobile-responsive=\"true\" class=\"mb-bootstrap-table text-nowrap\"></table>");
        lists.add("            </div>");
        lists.add("        </div>");
        lists.add("    </div>");
        lists.add("</div>");
        lists.add("<div data-th-include=\"\"></div>");
        lists.add("<script data-th-src=\"@{assets/layui.all.js}\"></script>");
        lists.add("<script>");

        lists.add("    var form = layui.form");
        lists.add("        ,layer = layui.layer;");
        lists.add("</script>");

        lists.add("<script  type=\"text/javascript\">");
        lists.add("$(document).ready(function(){");
        lists.add("    var searchForm=$(\"#" + className + "-search-form\");");
        lists.add("    var settings = {");
        lists.add("        url: ctx + \"/getDataList\",");
        lists.add("        pageSize: 10,");
        lists.add("        queryParams: function(params) {");
        lists.add("            return {");
        lists.add("                rows: params.limit,");
        lists.add("                page: params.offset / params.limit + 1,");
        for (int i = 0; i < fileds.size(); i++) {
            String filed = fileds.get(i);
            String str = "               " + filed + ":searchForm.find(\"input[id='" + filed + "']).val().trim()";
            if (i == fileds.size() - 1) {
                str = str + "";
            } else {
                str = str + ",";
            }
            lists.add(str);
        }
        lists.add("            };");
        lists.add("        },");
        lists.add("        columns: [{");
        lists.add("                checkbox: true");
        lists.add("            }, ");

        for (int i = 0; i < fileds.size(); i++) {
            String filed = fileds.get(i);
            String conmmon = filedComment.get(filed);

            String str = "        { field: '" + filed + "',visible:true,title:'" + conmmon
                    + "',formatter: function(value, row, index) {return value;}}";
            if (i == fileds.size() - 1) {
                str = str + "";
            } else {
                str = str + ",";
            }
            lists.add(str);
        }
        lists.add("]}");
        lists.add("   $MB.initTable('" + className + "Table', settings);");
        lists.add("});");
        lists.add("function search() {");
        lists.add("    $MB.refreshTable('" + className + "Table');");
        lists.add("}");
        lists.add("function deleteFunction() {");
        lists.add("    var selected = $(\"#" + className + "Table\").bootstrapTable('getSelections');");
        lists.add("    var selected_length = selected.length;");

        lists.add("    var contain = false;");
        lists.add("    if (!selected_length) {");
        lists.add("        $MB.n_warning('请勾选需要删除的数据！');");
        lists.add("        return;");
        lists.add("    }");
        lists.add("    var ids = \"\";");
        lists.add("    for (var i = 0; i < selected_length; i++) {");
        lists.add("        ids += selected[i]." + idFiled + ";");
        lists.add("        if (i != (selected_length - 1)){ ids += \",\"};");
        lists.add("    }");
        lists.add("    $MB.confirm({");
        lists.add("        text: \"确定删除选中的数据吗？\",");
        lists.add("        confirmButtonText: \"确定删除\"");
        lists.add("    }, function() {");
        lists.add(" $.post(ctx + '/delete', { \"ids\": ids }, function(r) {");
        lists.add("            if (r.code == 0) {");
        lists.add("                $MB.n_success(r.msg);");
        lists.add("                refresh();");
        lists.add("            } else {");
        lists.add("                $MB.n_danger(r.msg);");
        lists.add("            }");

        lists.add("        });");
        lists.add("    });");
        lists.add("}");

        lists.add("function updateFunction() {");
        lists.add("    var selected = $(\"#" + className + "Table\").bootstrapTable('getSelections');");
        lists.add("    var selected_length = selected.length;");
        lists.add("   if (!selected_length) {");
        lists.add("        $MB.n_warning('请勾选需要修改的数据！');");
        lists.add("        return;");
        lists.add("     }");
        lists.add("    if (selected_length > 1) {");
        lists.add("        $MB.n_warning('一次只能修改一条数据！');");
        lists.add("        return;");
        lists.add("    }");
        lists.add("    var id = selected[0]." + idFiled + ";");
        lists.add("    $.post(ctx + \"\", { \"id\": id }, function(r) {");
        lists.add("        if (r.code == 0) {");
        lists.add("         var $form = $('#" + className + "-add');");
        lists.add("         $form.modal();");
        lists.add("            var obj = r.msg;");
        lists.add("            $(\"#" + className + "-add-modal-title\").html('修改数据');");

        fileds.forEach((filed) -> {
            lists.add("            $form.find(\"input[id='" + filed + "']\").val(obj." + filed + ");");
        });

        lists.add("        } else {");
        lists.add("            $MB.n_danger(r.msg);");
        lists.add("        }");
        lists.add("    });");
        lists.add("}");

        lists.add("function initSelectFunction(url,id,input,fomId){");
        lists.add("   $.post(ctx + url, {}, function(r) {");
        lists.add("		var data = r.msg;");
        lists.add("		var option = \"\";");
        lists.add("		for (var i = 0; i < data.length; i++) {");
        lists.add("			option += \"<option value='\" + data[i].code + \"'>\"+ data[i].label + \"</option>\"");
        lists.add("		}");
        lists.add("		$('#'+fomId).find(input+\"[id='\"+id+\"']\").append(option);");
        lists.add("	    var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加()");
        lists.add("    	form.render(input);");
        lists.add("	});");
        lists.add("}");

        lists.add("	function initRole(url,id) {");
        lists.add("	    $.post(ctx + url, {}, function(r) {");
        lists.add("	        var data = r.rows;");
        lists.add("	        var option = \"\";");
        lists.add("	        for (var i = 0; i < data.length; i++) {");
        lists.add("	            option += \"<option value='\" + data[i].code + \"'>\" + data[i].label + \"</option>\"");
        lists.add("	        }");
        lists.add("	        $('#\"+id+\"').html(\"\").append(option);");
        lists.add("// 	        var options = {");
        lists.add("//	            selectAllText: '所有角色',");
        lists.add("//	            allSelected: '所有角色',");
        lists.add("//	            width: '100%',");
        lists.add("//	            onClose: function() {");
        lists.add("// 	                $roles.val($rolesSelect.val());");
        lists.add("//	                validator.element(\"input[name='roles']\");");
        lists.add("//	            }");
        lists.add("//	        }");
        lists.add("//	        $rolesSelect.multipleSelect(options);");
        lists.add("	    });");
        lists.add("	}");
        lists.add("	function createDeptTree(url,id) {");

        lists.add("	    $.post(ctx + url, {}, function(r) {");
        lists.add("	        if (r.code == 0) {");
        lists.add("	            var data = r.msg;");
        lists.add("	            $('#deptTree').jstree({");
        lists.add("	                \"core\": {");
        lists.add("	                    'data': data.children,");
        lists.add("	                    'multiple': false // 取消多选");
        lists.add("	                },");
        lists.add("	                \"state\": {");
        lists.add("	                    \"disabled\": true");
        lists.add("	                },");
        lists.add("	                \"checkbox\": {");
        lists.add("	                    \"three_state\": false // 取消选择父节点后选中所有子节点");
        lists.add("	                },");
        lists.add("	                \"plugins\": [\"wholerow\", \"checkbox\"]");
        lists.add("	            });");
        lists.add("	        } else {");
        lists.add("	            $MB.n_danger(r.msg);");
        lists.add("	        }");
        lists.add("	    });");
        lists.add("	}");
        lists.add("	function getDept(treeId,id) {");
        lists.add("	    var ref = $('#'+treeId).jstree(true);");
        lists.add("   $('#'+id).val(ref.get_selected()[0]);");
        lists.add(" }");

        lists.add("</script>");

        lists.add("</body>");
        lists.add("</html>");

        write(lists, path + "admin/", name + ".html");
    }

    private void chooseAdminEditLayUi(String path, String className) throws IOException {
        List<String> lists = new ArrayList<String>();
        String name = className + "LayUiAdd";
        lists.add(
                "<div class=\"modal fade\" id=\"" + className + "-add\" data-keyboard=\"false\" data-backdrop=\"static\" tabindex=\"-1\">");
        lists.add("    <div class=\"modal-dialog modal-lg\">");
        lists.add("        <div class=\"modal-content\">");
        lists.add("            <div class=\"modal-header\">");
        lists.add(
                "                <h3 class=\"modal-title pull-left\" id=\"" + className + "-add-modal-title\">新增</h3>");
        lists.add("            </div>");
        lists.add("            <div class=\"modal-body\">");
        lists.add("                <form id=\"" + className + "-add-form\">");

        for (String filed : fileds) {
            String common = filedComment.get(filed);
            lists.add("                    <div class=\"row\">");
            lists.add("                        <div class=\"col-sm-11\">");
            lists.add("                            <div class=\"input-group\">");
            lists.add("                                <span class=\"input-group-addon\" style=\"width:85px;\">");
            lists.add("					               	 " + common + "：");
            lists.add("					            </span>");
            lists.add("                                <div class=\"form-group\">");
            lists.add("                                    <input type=\"text\" id=\"" + filed + "\" name=\"" + filed
                    + "\" class=\"form-control\" style=\"width:300px\">");
            lists.add("                                </div>");
            lists.add("                            </div>");
            lists.add("                        </div>");
            lists.add("                    </div>");
        }

        lists.add("            <div class=\"modal-footer\">");
        lists.add("                <button type=\"button\" class=\"btn btn-save\" id=\"" + className
                + "-add-button\" name=\"save\">保存</button>");
        lists.add("                <button type=\"button\" class=\"btn btn-secondary btn-close\">关闭</button>");
        lists.add("                <button class=\"btn-hide\"></button>");
        lists.add("            </div>");
        lists.add("            </form>");
        lists.add("        </div>");
        lists.add("    </div>");
        lists.add("</div>");
        lists.add("</div>");
        lists.add("<script type=\"text/javascript\">");
        lists.add("var validator;");

        lists.add("	var $form = $(\"#" + className + "-add-form\");");
        lists.add("$(document).ready(function(){");
        lists.add("  validateRule();");
//		lists.add("	function initTree(url,id) {");
//		lists.add("	    $.post(ctx + url, {}, function(r) {");
//		lists.add("	        if (r.code == 0) {");
        lists.add("	});");
        lists.add("	function closeModal() {");
        lists.add("	    validator.resetForm();");
        lists.add("}");
        lists.add("	function validateRule() {");
        lists.add("	    var icon = \"<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> \";");
        lists.add("	    validator = $form.validate({");
        lists.add("	        rules: {");

        for (int i = 0; i < fileds.size(); i++) {
            String filed = fileds.get(i);
            Integer length = filedLength.get(filed);

            lists.add(filed + ":{");
            if (null == length) {
                lists.add("  required: true");
            } else {
                lists.add("  required: true,");
                lists.add("	 maxlength: " + length);
            }
            if (i == fileds.size() - 1) {
                lists.add("}");
            } else {
                lists.add("},");
            }

        }

        lists.add("	        },");
        lists.add("	        errorPlacement: function(error, element) {");
        lists.add("	            if (element.is(\":checkbox\") || element.is(\":radio\")) {");
        lists.add("	                error.appendTo(element.parent().parent());");
        lists.add("	            } else {");
        lists.add("	                error.insertAfter(element);");
        lists.add("	            }");
        lists.add("	        },");
        lists.add("	        messages: {");

        for (int i = 0; i < fileds.size(); i++) {
            String filed = fileds.get(i);
            Integer length = filedLength.get(filed);
            String common = filedComment.get(filed);

            lists.add(filed + ":{");
            if (null == length) {
                lists.add("  required: icon+\"" + common + "  不能为空\"");
            } else {
                lists.add("  required: icon+\"" + common + "  不能为空\",");
                lists.add("	 maxlength: \"最大长度不能超过" + length + "\"");
            }
            if (i == fileds.size() - 1) {
                lists.add("}");
            } else {
                lists.add("},");
            }
        }

        lists.add("	        }");
        lists.add("	    });");
        lists.add("	}");

        lists.add(" function save(url){");
        lists.add("  //getDept();");
        lists.add("  var validator = $userAddForm.validate();");
        lists.add("	 var flag = validator.form();");
        lists.add("  if (flag) {");
        lists.add("   $.post(ctx + url, $form.serialize(), function(r) {");
        lists.add("       if (r.code == 0) {");
        lists.add("           closeModal();");
        lists.add("           $MB.n_success(r.msg);");
        lists.add("           $MB.refreshTable(\"" + className + "Table\");");
        lists.add("       } else { $MB.n_danger(r.msg, '.modal');}");
        lists.add("     });");
        lists.add("   }");
        lists.add(" }");
        lists.add("</script>");
        write(lists, path + "admin/", name + ".html");
    }

    private void chooseAdminListJsp(String path, String className) throws IOException {
        List<String> lists = new ArrayList<String>();
        String name = className + "List";
        lists.add("<%@ page language=\"java\" contentType=\"text/html;charset=UTF-8\" pageEncoding=\"UTF-8\"%>");
        lists.add("<%@ include file=\"/views/include/taglib.jsp\"%>");
        lists.add("<%@ include file=\"/views/include/include.jsp\"%>");
        lists.add("<!DOCTYPE html>");
        lists.add("<html style=\"overflow: hidden;\">");
        lists.add("<head>");
        lists.add("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        lists.add("<meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />");
        lists.add("<title>列表</title>");
        lists.add("</head>");
        lists.add("<body>");
        lists.add("	<div style=\"width:100%;height:100%;\">");
        lists.add("	  <div style=\"width:100%;\">");
        lists.add("		 <div class=\"mini-toolbar\" style=\"border-bottom:0;padding:0px;\">");
        lists.add("		    <table style=\"width:100%;\">");
        lists.add("			  <tr>");
        lists.add("				<td style=\"width:100%;\">");
        lists.add("				   <shiro:hasPermission name=\"game:type:createBtn:edit\">");
        lists.add("					  <a class=\"mini-button\" iconCls=\"icon-add\" onclick=\"add()\">增加</a>");
        lists.add("					</shiro:hasPermission>");
        lists.add("				   <shiro:hasPermission name=\"game:type:editBtn:edit\">");
        lists.add(
                "					  <a id=\"editBtn\" class=\"mini-button\" iconCls=\"icon-edit\" onclick=\"edit()\">修改</a>");
        lists.add("					</shiro:hasPermission>");
        lists.add("				   <shiro:hasPermission name=\"game:type:deleteBtn:edit\">");
        lists.add(
                "					  <a id=\"delBtn\" class=\"mini-button\" iconCls=\"icon-cancel\" onclick=\"remove()\">删除</a>");
        lists.add("					</shiro:hasPermission>");
        lists.add("				   <a class=\"mini-button\" iconCls=\"icon-reload\" onclick=\"refresh()\">刷新</a>");
        lists.add("             </td>");
        lists.add("           </tr>");
        lists.add("		     </table>");
        lists.add("		    </div>");
        lists.add("		</div>");
        lists.add("		<div class=\"mini-fit\">");
        lists.add(
                "		   <div id=\"grid\" class=\"mini-datagrid\" style=\"width:100%;height:100%;\" allowResize=\"false\" showReloadButton=\"false\" allowAlternating=\"true\"");
        lists.add(
                "          defaultColumnWidth=\"80\" showFilterRow=\"false\" allowCellSelect=\"false\" allowCellEdit=\"false\" multiSelect=\"true\">");
        lists.add("			<div property=\"columns\">");
        lists.add("           <div type=\"checkcolumn\"></div>");
        fileds.forEach((filed) -> {
            String commons = filedComment.get(filed);
            lists.add("        <div field=\"" + filed + "\" width=\"20\" headerAlign=\"left\" align=\"left\">" + commons
                    + "</div>");
        });
        lists.add("			</div>");
        lists.add("		  </div>");
        lists.add("		</div>");
        lists.add("	</div>");
        lists.add("	<script src=\"${ctxStatic}/js//" + name + ".js?v=1.0\" type=\"text/javascript\"></script>");
        lists.add("</body>");
        lists.add("</html>");

        write(lists, path + "admin/", name + ".jsp");
    }

    private void chooseAdminController(String path, String className) throws IOException {
        List<String> lists = new ArrayList<String>();
        String name = className + "AdminController";
        String manager = formatFiledClass(managerSevice);
        String controllerName = formatFiledClass(className);

        lists.add("import com.fulihui.kirin.common.web.BaseController;");
        lists.add("import org.springframework.stereotype.Controller;");
        lists.add("import org.springframework.web.bind.annotation.RequestMapping;");
        lists.add("import org.springframework.web.bind.annotation.ResponseBody;");
        lists.add("import java.util.List;");
        lists.add("import org.springframework.beans.factory.annotation.Autowired;");
        lists.add("import org.near.webmvcsupport.view.JsonResult;");
        lists.add("import org.near.webmvcsupport.view.JsonResultBuilder;");
        lists.add("@Controller");
        lists.add("@RequestMapping(value = \"${adminPath}/\")");
        lists.add("public class " + name + " extends BaseController{");
        lists.add("\t @Autowired");
        lists.add("\t private " + managerSevice + "AdminImpl " + manager + ";");
        lists.add("\t @RequiresPermissions(\":" + controllerName + ":view\")");
        lists.add("\t  @RequestMapping(value = \"list\")");
        lists.add("\t  public String list(HttpServletRequest request,HttpServletResponse response) {");
        lists.add("\t\t return \"" + controllerName + "List\";");
        lists.add("\t }");
        lists.add("\t @RequiresPermissions(\":" + controllerName + ":view\")");
        lists.add("\t @RequestMapping(value = \"toAdd\")");
        lists.add("\t public String toAdd() {");
        lists.add("\t\t  " + requestName + " form = new " + requestName + "(); ");
        lists.add("\t\t request.setAttribute(\"vo\",vo);");
        lists.add("\t\t request.setAttribute(\"action\",\"insert\");");
        lists.add("\t\t return \"\";");
        lists.add("\t }");
        lists.add("\t @RequiresPermissions(value = \"view\")");
        lists.add("\t @RequestMapping(value = \"toEdit/{id}\", method = {RequestMethod.GET})");
        lists.add("\t public String toEdit(HttpServletRequest request, @PathVariable(\"id\") Long id) {");
        lists.add("\t\t  " + requestName + " form = new " + requestName + "(); ");
        lists.add("\t\t  form.setId(id);");
        lists.add("\t\t   " + voName + " vo = " + manager + ".selectById(form);");
        lists.add("\t\t request.setAttribute(\"vo\",vo);");
        lists.add("\t\t request.setAttribute(\"action\",\"update\");");
        lists.add("\t\t return \"\";");
        lists.add("\t }");
        lists.add("\t @RequiresPermissions(value = \":" + controllerName + ":view\")");
        lists.add("\t @RequestMapping(value = \"getDataList\")");
        lists.add("\t @ResponseBody");
        lists.add("\t public Map<String, Object> getDataList(" + requestName + " form, HttpServletRequest request) {");
        lists.add("\t\t form.setRows(PageUtil.getPageSize(request)); ");
        lists.add("\t\t form.setPage(PageUtil.getPageNo(request));");
        lists.add("\t\t return " + manager + ".selectLimit(form); ");
        lists.add("\t} ");
        lists.add("\t @RequiresPermissions(value = \":" + controllerName + ":edit,createBtn\")");
        lists.add("\t @ResponseBody");
        lists.add("\t @RequestMapping(value = \"insert\", method = {RequestMethod.POST})");
        lists.add("\t public JsonResult<Boolean> insert(" + requestName + " form) {");
        lists.add("\t\t  BaseResult result = " + manager + ".insert(form);");
        lists.add("\t\t return chooseResult(result);");
        lists.add("\t }");
        lists.add("\t @RequiresPermissions(value = \":" + controllerName + ":edit,editBtn\")");
        lists.add("\t @ResponseBody");
        lists.add("\t @RequestMapping(value = \"update\", method = {RequestMethod.POST})");
        lists.add("\t public JsonResult<Boolean> update(" + requestName + " form) {");
        lists.add("\t\t  if(Objects.isNull(form.getId())){");
        lists.add("\t \t\t  return JsonResultBuilder.fail(\"-1\", \"ID不能为空！\");");
        lists.add("\t\t  }");
        lists.add("\t\t BaseResult result = " + manager + ".update(form);");
        lists.add("\t\t return chooseResult(result);");
        lists.add("\t }");
        lists.add("\t @RequiresPermissions(\":type:" + controllerName + ",delteBtn\")");
        lists.add("\t @RequestMapping(value = \"deleteByIds\", method = {RequestMethod.POST})");
        lists.add("\t @ResponseBody");
        lists.add("\t public JsonResult deleteByIds(@RequestParam(\"ids[]\") List<Long> ids) {");
        lists.add("\t\t  if(CollectionUtils.isEmpty(ids)){");
        lists.add("\t\t\t  return JsonResultBuilder.fail(\"-1\", \"参数不能为空！\"); ");
        lists.add("\t\t } ");
        lists.add("\t  BaseResult result = " + manager + ".del(ids);");
        lists.add("\t\t return chooseResult(result);");
        lists.add("\t }");
        lists.add("\t private JsonResult<Boolean> chooseResult(BaseResult result){");
        lists.add("\t\t if(result == null){");
        lists.add("\t\t\t return JsonResultBuilder.fail(\"-1\", \"结果为空\");");
        lists.add("\t\t }else if (result.getErrcode() != 0) {");
        lists.add("\t\t\t return JsonResultBuilder.fail(String.valueOf(result.getErrcode()), result.getErrmsg());");
        lists.add("\t\t }");
        lists.add("\t\t return JsonResultBuilder.succ(result.getErrcode() == 0 ? true : false);");
        lists.add("\t }");

        write(lists, path + "admin/", name + ".java");
    }

    private void chooseController(String path, String className, String serviceStr, String voStr, String dtoStr, String entityStr, String tableName, String packageStr) throws IOException {
        if (StringUtils.isEmpty(packageStr)) {
            return;
        }
        List<String> lists = new ArrayList<String>();
        String name = className + "Controller";
        String manager = formatFiledClass(serviceName);
        lists.add("package " + packageStr + ";");
        lists.add("import org.springframework.beans.factory.annotation.Autowired;");
        lists.add("import org.springframework.web.bind.annotation.RestController;");
        lists.add("import org.springframework.web.bind.annotation.RequestMapping;");
        lists.add("import io.swagger.annotations.Api;");
        lists.add("import org.springframework.web.bind.annotation.*;");
        lists.add("import io.swagger.annotations.ApiOperation;");
        lists.add("import org.springframework.beans.BeanUtils;");
        lists.add("import java.util.ArrayList;");
        lists.add("import java.util.List;");

        lists.add("import java.util.Objects;");
        lists.add("import org.apache.shiro.authz.annotation.RequiresPermissions;");
        lists.add("import io.swagger.annotations.ApiOperation;");
        lists.add("import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;");
        lists.add("import org.apache.commons.collections4.CollectionUtils;");
        lists.add("import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;");
        lists.add("import com.baomidou.mybatisplus.core.metadata.IPage;");
        lists.add("import com.baomidou.mybatisplus.extension.plugins.pagination.Page;");
        lists.add("import io.swagger.annotations.ApiImplicitParam;");
        lists.add("import io.swagger.annotations.ApiImplicitParams;");
        lists.add("import org.jeecg.common.aspect.annotation.PermissionData;");

//        if(StringUtils.isNotEmpty(pageResultVOImpl)) {
//            lists.add("import "+pageResultVOImpl+";");
//        }
        String resultClass = "";

        if (StringUtils.isNotEmpty(responseDataImpl)) {
            lists.add("import " + responseDataImpl + ";");
            resultClass = StringUtils.substringAfterLast(responseDataImpl, ".");
        }
        lists.add("import " + constant + ";");
        String constantClass = StringUtils.substringAfterLast(constant, ".");


//        lists.add("import com.whrhkj.accounting.common.utils.MathUtils;");
        lists.add("import " + serviceStr + ";");
        lists.add("import " + voStr + ";");
        lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + addDTO + ";");
        lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + updateDTO + ";");
        if (statucFlag) {
            lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + updateStatusDTO + ";");
        }
        lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + queryDTO + ";");
        lists.add("import " + entityStr + ";");

        String url = StringUtils.replace(StringUtils.replace(tableName, "_", "/"), "-", "/").toLowerCase();
        if (StringUtils.isNotEmpty(entity.getStartCharacter())) {
            url = entity.getStartCharacter() + "/" + url;
        }
        String authority = StringUtils.replace(url, "/", ":");
        String getIdMethod = getMethodNameMap.get(idFiled);

        lists.add("@RestController");
        lists.add("@RequestMapping(\"" + url + "\")");
        lists.add("@Api(\" \")");
        lists.add("public class " + name + "{");
        lists.add("\t @Autowired");
        lists.add("\t private " + serviceName + " " + manager + ";");


        lists.add("\t @PostMapping(value=\"/list/limit/{page}/{pageLimit}\")");
        lists.add("\t @ApiOperation(\"\")");
        lists.add("@PermissionData(pageComponent = \"" + url + "/list/limit\")");
        lists.add("@RequiresPermissions(\"" + authority + ":list:limit\")");
        lists.add("\t @ApiImplicitParams({");
        lists.add("\t\t @ApiImplicitParam(paramType = \"body\", name = \"request\", value = \"\",dataType=\"" + queryDTO + "\"),");
        lists.add("\t\t @ApiImplicitParam(paramType = \"path\", name = \"page\", value = \"当前页数\", example = \"1\"),");
        lists.add("\t\t @ApiImplicitParam(paramType = \"path\", name = \"pageLimit\", value = \"每页条数\", example = \"1\")");
        lists.add("\t })");
        lists.add("\t public " + resultClass + "<IPage<" + voName + ">> listLimit(@RequestBody " + queryDTO + " request,@PathVariable Integer page,@PathVariable Integer pageLimit) {");
//        lists.add("\t\t Page<"+entityName+"> limitPage = " + manager + ".selectLimitPage(convert(request),page,pageLimit);");
//        lists.add("\t\t  PageResultVO<"+voName+"> resultVO = new PageResultVO(page, pageLimit, MathUtils.convertToInt(limitPage.getTotal()), convert(limitPage.getResult()));");
        lists.add("\t\t " + entityName + " entity = convert(request);");
        lists.add("\t\t IPage response = " + manager + ".page(new Page<" + entityName + ">(page,pageLimit),new QueryWrapper<" + entityName + ">(entity));");
        lists.add("\t\t  return " + responseDateMethod + "(convert(response));");
        lists.add("\t}");

//        lists.add("\t @RequiresPermissions(value = \"view\")");


        lists.add("\t @GetMapping(value = \"view/{" + idFiled + "}\")");
        lists.add("\t @ApiOperation(\"\")");
//        lists.add("\t @ResponseBody");
        lists.add("@PermissionData(pageComponent = \"" + url + "/view\")");
        lists.add("@RequiresPermissions(\"" + authority + ":view\")");
        String setIdMethod = setMethodNameMap.get(idFiled);
        lists.add("@ApiImplicitParams({");
        String idType = filedType.get(idFiled);
        if (ArrayUtils.contains(nums, idType)) {
            lists.add("\t\t @ApiImplicitParam(paramType = \"path\", name = \"" + idFiled + "\", value = \"主键\", example = \"1\")");
        } else {
            lists.add("\t\t @ApiImplicitParam(paramType = \"path\", name = \"" + idFiled + "\", value = \"主键\")");
        }
        lists.add("\t })");
        lists.add("\t public " + resultClass + "<" + voName + "> view( @PathVariable(\"" + idFiled + "\") " + idType + " " + idFiled + ") {");
//        lists.add("\t\t  " + entityName + " form = new " + entityName + "(); ");
//        lists.add("\t\t  form."+setIdMethod+"("+idFiled+");");
        lists.add("\t\t   " + entityName + " source = " + manager + ".getById(" + idFiled + ");");
        lists.add("\t\t return  " + responseDateMethod + "(convert(source));");
        lists.add("\t }");


        lists.add("\t @PostMapping(value=\"/add\")");
        lists.add("\t @ApiOperation(\"\")");
//        lists.add("@PermissionData(pageComponent = \"" + url + "/add\")");
        lists.add("@RequiresPermissions(\"" + authority + ":add\")");
        lists.add("\t @ApiImplicitParams({");
        lists.add("\t\t @ApiImplicitParam(paramType = \"body\", name = \"request\", value = \"\",dataType=\"" + addDTO + "\")");
        lists.add("\t })");
        lists.add("\t public " + resultClass + "<Object> add(@RequestBody " + addDTO + " request) {");
        lists.add("\t\t " + entityName + " entity = convert(request); ");
        lists.add("\t\t boolean flag = " + manager + ".save(entity);");
        lists.add(" return flag?" + responseDateMethod + "(flag):" + resultClass + ".error(" + constantClass + ".COUNT_IS_ZERO.getCode(), " + constantClass + ".COUNT_IS_ZERO.getMessage());");
        lists.add("\t }");


        lists.add("\t @PutMapping(value=\"/update\")");
        lists.add("\t @ApiOperation(\"\")");
//        lists.add("@PermissionData(pageComponent = \"" + url + "/update\")");
        lists.add("@RequiresPermissions(\"" + authority + ":update\")");
        lists.add("\t @ApiImplicitParams({");
        lists.add("\t\t @ApiImplicitParam(paramType = \"body\", name = \"request\", value = \"\",dataType=\"" + updateDTO + "\")");
        lists.add("\t })");
        lists.add("\t public " + resultClass + "<Object> update(@RequestBody " + updateDTO + " request) {");

        lists.add("\t\t " + entityName + " entity = convert(request); ");
        lists.add("\t\t boolean flag =  " + manager + ".update(entity,new UpdateWrapper<" + entityName + ">().lambda().eq(" + entityName + "::" + getIdMethod + ",entity." + getIdMethod + "()));");
//        lists.add("\t\t int count =  " + manager + ".update(entity);");
//        lists.add("\t\t boolean flag = Objects.equals(count, Constant.ONE); ");
        lists.add("\t\t return flag ? " + responseDateMethod + "(flag):" + resultClass + ".error(" + constantClass + ".COUNT_IS_ZERO.getCode(), " + constantClass + ".COUNT_IS_ZERO.getMessage()) ;");
        lists.add("\t }");
        if (statucFlag) {

            lists.add("\t @DeleteMapping(value=\"/update/status\")");
            lists.add("\t @ApiOperation(\"\")");
//            lists.add("@PermissionData(pageComponent = \"" + url + "/update/status\")");
            lists.add("@RequiresPermissions(\"" + authority + ":update:status\")");
            lists.add("\t @ApiImplicitParams({");
            lists.add("\t\t @ApiImplicitParam(paramType = \"body\", name = \"request\", value = \"\",dataType=\"" + updateStatusDTO + "\")");
            lists.add("\t })");
            lists.add("\t public " + resultClass + "<Object> updateState(@RequestBody " + updateStatusDTO + " request) {");
            lists.add("\t\t " + entityName + " entity = convert(request); ");
//        lists.add("\t\t int count = " + manager + ".update(convert(request));");
//        lists.add("\t\t boolean flag = Objects.equals(count, Constant.ONE); ");

            lists.add("\t\t boolean flag =  " + manager + ".update(entity,new UpdateWrapper<" + entityName + ">().lambda().eq(" + entityName + "::" + getIdMethod + ",entity." + getIdMethod + "()));");
            lists.add("\t\t return flag ? " + responseDateMethod + "(flag):" + resultClass + ".error(" + constantClass + ".COUNT_IS_ZERO.getCode(), " + constantClass + ".COUNT_IS_ZERO.getMessage()) ;");
            lists.add("\t }");
        } else {

            lists.add("\t @RequestMapping(value=\"/del\",method=RequestMethod.POST)");
            lists.add("\t @ApiOperation(\"\")");
//            lists.add("@PermissionData(pageComponent = \"" + url + "/del\")");
            lists.add("@RequiresPermissions(\"" + authority + ":del\")");
            lists.add("\t @ApiImplicitParams({");
            lists.add("\t\t @ApiImplicitParam(paramType = \"body\", name = \"request\", value = \"\",dataType=\"" + queryDTO + "\")");
            lists.add("\t })");
            lists.add("\t public " + resultClass + "<Object> del(@RequestBody " + queryDTO + " request) {");
//            lists.add("\t\t " + entityName + " entity = convert(request); ");
            lists.add("\t\t  boolean flag = " + manager + ".removeById(request." + getIdMethod + "());");
//            lists.add("\t\t int count =  " + manager + ".update(request);");
//            lists.add("\t\t return Objects.equals(count, Constant.ONE) ? ResponseData.success(count):ResponseData.error(CodeConstant.COUNT_IS_ZERO.getCode(), CodeConstant.COUNT_IS_ZERO.getMessage()) ;");
            lists.add("\t\t return flag ? " + responseDateMethod + "(flag):" + resultClass + ".error(" + constantClass + ".COUNT_IS_ZERO.getCode(), " + constantClass + ".COUNT_IS_ZERO.getMessage()) ;");
            lists.add("\t }");
        }


//        lists.add("\t @RequestMapping(value=\"/del\",method=RequestMethod.POST)");
//        lists.add("\t @ApiOperation(\"\")");
//        lists.add("\t public ResponseData<Boolean> del(@RequestBody " + dtoName + " request) {");
//        lists.add("\t\t int count =  " + manager + ".update(request);");
//        lists.add("\t\t return Objects.equals(count, Constant.ONE) ? ResponseData.success(count):ResponseData.error(CodeConstant.COUNT_IS_ZERO.getCode(), CodeConstant.COUNT_IS_ZERO.getMessage()) ;");
//        lists.add("\t }");

        lists.add("\t private " + entityName + " convert(" + queryDTO + " source) {");
        lists.add("\t\t  if (Objects.isNull(source)) {");
        lists.add("\t\t\t   return null;");
        lists.add("\t\t }");
        lists.add("\t\t  " + entityName + " target = new " + entityName + "();");
        lists.add("\t\t  BeanUtils.copyProperties(source, target);");
        lists.add("\t\t return target;");
        lists.add("\t\t }");

        lists.add("\t private " + entityName + " convert(" + updateDTO + " source) {");
        lists.add("\t\t  if (Objects.isNull(source)) {");
        lists.add("\t\t\t   return null;");
        lists.add("\t\t }");
        lists.add("\t\t  " + entityName + " target = new " + entityName + "();");
        lists.add("\t\t  BeanUtils.copyProperties(source, target);");
        lists.add("\t\t return target;");
        lists.add("\t\t }");

        if (statucFlag) {
            lists.add("\t private " + entityName + " convert(" + updateStatusDTO + " source) {");
            lists.add("\t\t  if (Objects.isNull(source)) {");
            lists.add("\t\t\t   return null;");
            lists.add("\t\t }");
            lists.add("\t\t  " + entityName + " target = new " + entityName + "();");
            lists.add("\t\t  BeanUtils.copyProperties(source, target);");
            lists.add("\t\t return target;");
            lists.add("\t\t }");
        }

        lists.add("\t private " + entityName + " convert(" + addDTO + " source) {");
        lists.add("\t\t  if (Objects.isNull(source)) {");
        lists.add("\t\t\t   return null;");
        lists.add("\t\t }");
        lists.add("\t\t  " + entityName + " target = new " + entityName + "();");
        lists.add("\t\t  BeanUtils.copyProperties(source, target);");
        lists.add("\t\t return target;");
        lists.add("\t\t }");

        lists.add("\t\t private " + voName + " convert(" + entityName + " source) {");
        lists.add("\t\t  if (Objects.isNull(source)) {");
        lists.add("\t\t\t   return null;");
        lists.add("\t\t }");
        lists.add("\t\t  " + voName + " target = new " + voName + "();");
        lists.add("\t\t  BeanUtils.copyProperties(source, target);");
        lists.add("\t\t return target;");
        lists.add("\t\t }");
        lists.add("\t\t private List<" + voName + "> convert(List<" + entityName + "> sources) {");
        lists.add("\t\t  if (CollectionUtils.isEmpty(sources)) {");
        lists.add("\t\t\t return null;");
        lists.add("\t\t  }");
        lists.add("\t\t  List<" + voName + "> targets = new ArrayList<>();");
        lists.add("\t\t  sources.forEach(source -> {");
        lists.add("\t\t\t " + voName + " target = convert(source);");
        lists.add("\t\t\t  if (Objects.nonNull(target)) {");
        lists.add("\t\t\t\t targets.add(target);");
        lists.add("\t\t\t   }");
        lists.add("\t\t });");
        lists.add("\t\t return targets;");
        lists.add("\t\t}");

        lists.add("\t\t private IPage<" + voName + "> convert(IPage<" + entityName + "> source) {");
        lists.add("\t\t  if (Objects.isNull(source)) {");
        lists.add("\t\t\t return null;");
        lists.add("\t\t  }");
        lists.add("\t\t IPage<" + voName + "> target = new Page<>();");
        lists.add("\t\t BeanUtils.copyProperties(source,target);");
        lists.add("\t\t List<" + voName + "> " + voName + "s = convert(source.getRecords());");

        lists.add("\t\t target.setRecords(" + voName + "S);");
        lists.add("\t\t return target;");
        lists.add("\t\t}");

        lists.add("}");


        write(lists, path, name + ".java");
    }

    private void chooseManagerSevice(String path) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.result.web.PageView;");
        lists.add("public interface " + managerSevice + " {");
        lists.add("/**分页查询*/");
        lists.add("\t PageView<" + voName + "> selectLimit(" + requestName + " request);");

        lists.add("/**分页查询*/");
        lists.add("\t " + voName + " selectById(" + requestName + " request);");

        lists.add("\t/**新增*/");
        lists.add("\t BaseResult insert(" + requestName + " request);");

        lists.add("\t /**修改*/");
        lists.add("\t BaseResult update(" + requestName + " request);");

        lists.add("\t /**修改状态*/");
        lists.add("\t BaseResult updateState(" + requestName + " request);");

        lists.add("\t/**删除*/");
        lists.add("\t BaseResult deleteById(List<Long> ids);");
        write(lists, path + "api/", managerSevice + ".java");
    }

    private void chooseManagerServiceImpl(String path, String className) throws IOException {
        String name = managerSevice + "Impl";
        String filedServiceName = formatFiledClass(serviceName);

        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.result.web.PageView;");
        lists.add("import org.springframework.stereotype.Service;");
        lists.add("import com.alibaba.dubbo.config.annotation.Reference;");
        lists.add("import org.slf4j.Logger;");
        lists.add("import org.slf4j.LoggerFactory;");

        lists.add("@Service");
        lists.add("public class " + name + " implements " + mapperName + "{");
        lists.add("\t @Reference(version = \"1.0.0\")");
        lists.add("\t private " + serviceName + " " + filedServiceName + ";");
        lists.add("\t private static final Logger LOGGER = LoggerFactory.getLogger(" + name + ".class);");
        lists.add("\t@Override");
        lists.add("\t public PageView<" + dtoName + "> selectLimit(" + requestName + " request){");
        lists.add("\t\t List<" + voName + "> lists = new ArrayList<" + voName + ">();");
        lists.add("//\t\t Map<String, Object> returnMap = new HashMap<String, Object>();");
        lists.add("\t\t try {");
        lists.add("\t\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t\t " + resultName + " result = " + filedServiceName + ".selectLimitPage(request);");
        lists.add("\t\t\t if (result.isSuccess() && !CollectionUtils.isEmpty(result.getValues())) {");
        lists.add("//\t\t\t\t returnMap.put(\"total\", result.getTotalRows());");
        lists.add(
                "\t\t\t\t\t List<" + dtoName + "> lists = new ArrayList<" + dtoName + ">(returnMap.getValues.size())");
        lists.add("\t\t\t\t result.getValues().forEach((dto) -> {");
        lists.add("\t\t\t\t\t" + voName + " vo = new " + voName + "();");
        lists.add("\t\t\t\t\t vo.copy(dto)");
        lists.add("\t\t\t\t\t lists.add(vo);");
        lists.add("\t\t\t\t });");
        lists.add("//\t\t\t returnMap.put(\"data\", lists);");
        lists.add("\t\t\t}");
        lists.add(
                "\t\t return PageViewBuilder.build(lists, request.getPage(), request.getRows(), result.getTotalRows());");
        lists.add("\t\t } catch (Exception e) {");
        lists.add("\t\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("//\t\t\t returnMap.put(\"errorMsg\", e.getMessage());");
        lists.add("\t\t\t return PageViewBuilder.build(lists, 0, request.getRows(), 0);");
        lists.add("\t\t}");
        lists.add("//\t\t return returnMap;");
        lists.add("\t}");

        lists.add("\t pubilc " + voName + " selectById(" + requestName + " request){");
        lists.add("\t\t try{");
        lists.add("\t\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t\t " + dtoName + " dto = " + filedServiceName + ".selectById(request);");
        lists.add("\t\t\t " + voName + " target = new " + voName + "();");
        lists.add("\t\t\t target.copy(dto);");
        lists.add("\t\t\t return target;");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t}");
        lists.add("\t return new " + voName + "();");
        lists.add("}");

        lists.add("@Override");
        lists.add("public BaseResult insert(" + requestName + " request){");
        lists.add("\t try {");
        lists.add("\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t return " + filedServiceName + ".insert(request);");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t\t return RpcResultBuilder.fail(Errors.Commons.SAVE_FAILED);");
        lists.add("\t}");
        lists.add("}");

        lists.add("@Override");
        lists.add("public BaseResult update(" + requestName + " request){");
        lists.add("\t try {");
        lists.add("\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t return " + filedServiceName + ".update(request);");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t\t return RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);");
        lists.add("\t}");
        lists.add("}");

        lists.add("//@Override");
        lists.add("//public BaseResult updateState(" + requestName + " request){");
        lists.add("//\t try {");
        lists.add("//\t\t LOGGER.info(\"{}\",request);");
        lists.add("//\t\t return " + filedServiceName + ".updateState(request);");
        lists.add("//} catch (Exception e) {");
        lists.add("//\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("//\t\t return RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);");
        lists.add("//\t}");
        lists.add("//}");

        lists.add("//@Override");
        lists.add("//public BaseResult deleteById(List<Long> ids){");
        lists.add("//\t try {");
        lists.add("//\t\t LOGGER.info(\"{}\",ids);");
        lists.add("//\t\t return " + filedServiceName + ".deleteById(ids);");
        lists.add("//} catch (Exception e) {");
        lists.add("//\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("//\t\t return RpcResultBuilder.fail(Errors.Commons.DELETE_FAILED);");
        lists.add("//\t}");
        lists.add("//}");
        lists.add("}");

        write(lists, path + "api/", name + ".java");

    }

    private void chooseManagerAdminServiceImpl(String path, String className) throws IOException {
        String name = managerSevice + "AdminImpl";
        String filedServiceName = formatFiledClass(serviceName);

        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.result.web.PageView;");
        lists.add("import org.springframework.stereotype.Service;");
        lists.add("import com.alibaba.dubbo.config.annotation.Reference;");
        lists.add("import org.slf4j.Logger;");
        lists.add("import org.slf4j.LoggerFactory;");

        lists.add("@Service");
        lists.add("public class " + name + "{");
        lists.add("\t @Autowired");
        lists.add("\t  @Override");
        lists.add("\t private " + serviceName + " " + filedServiceName + ";");
        lists.add("\t private static final Logger LOGGER = LoggerFactory.getLogger(" + name + ".class);");
        lists.add("\t@Override");
        lists.add("\t public Map<String, Object>  selectLimit(" + requestName + " request){");
        lists.add("\t\t Map<String, Object> returnMap = new HashMap<String, Object>();");
        lists.add("\t\t try {");
        lists.add("\t\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t\t " + resultName + " result = " + filedServiceName + ".selectLimitPage(request);");
        lists.add("\t\t\t if (null != result && result.isSuccess() && !CollectionUtils.isEmpty(result.getValues())) {");
        lists.add("\t\t\t\t returnMap.put(\"total\", result.getTotalRows());");
        lists.add("\t\t\t\t result.getValues().forEach((dto) -> {");
        lists.add("\t\t\t\t\t" + voName + " vo = new " + voName + "();");
        lists.add("\t\t\t\t\t vo.copy(dto)");
        lists.add("\t\t\t\t\t lists.add(vo);");
        lists.add("\t\t\t\t });");
        lists.add("\t\t\t returnMap.put(\"data\", lists);");
        lists.add("\t\t\t}");
        lists.add("\t\t returnMap;");
        lists.add("\t\t } catch (Exception e) {");
        lists.add("\t\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t\t\t returnMap.put(\"errorMsg\", e.getMessage());");
        lists.add("\t\t\t ");
        lists.add("\t\t}");
        lists.add("\t\t return returnMap;");
        lists.add("\t}");
        lists.add("\t  @Override");
        lists.add("\t pubilc " + voName + " selectById(" + requestName + " request){");
        lists.add("\t\t try{");
        lists.add("\t\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t\t SimpleResult<" + dtoName + "> result = " + filedServiceName + ".selectById(request);");
        lists.add("\t\t\t " + voName + " target = new " + voName + "();");
        lists.add("\t\t\t if (null != result && result.isSuccess()) {");
        lists.add("\t\t\t\t target.copy(dto);");
        lists.add("\t\t\t}");
        lists.add("\t\t\t return target;");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t}");
        lists.add("\t return new " + voName + "();");
        lists.add("}");

        lists.add("@Override");
        lists.add("public BaseResult insert(" + requestName + " request){");
        lists.add("\t try {");
        lists.add("\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t return " + filedServiceName + ".insert(request);");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t\t return RpcResultBuilder.fail(Errors.Commons.SAVE_FAILED);");
        lists.add("\t}");
        lists.add("}");

        lists.add("@Override");
        lists.add("public BaseResult update(" + requestName + " request){");
        lists.add("\t try {");
        lists.add("\t\t LOGGER.info(\"{}\",request);");
        lists.add("\t\t return " + filedServiceName + ".update(request);");
        lists.add("} catch (Exception e) {");
        lists.add("\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("\t\t return RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);");
        lists.add("\t}");
        lists.add("}");

        lists.add("//@Override");
        lists.add("//public BaseResult updateState(" + requestName + " request){");
        lists.add("//\t try {");
        lists.add("//\t\t LOGGER.info(\"{}\",request);");
        lists.add("//\t\t return " + filedServiceName + ".updateState(request);");
        lists.add("//} catch (Exception e) {");
        lists.add("//\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("//\t\t return RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);");
        lists.add("//\t}");
        lists.add("//}");

        lists.add("//@Override");
        lists.add("//public BaseResult deleteById(List<Long> ids){");
        lists.add("//\t try {");
        lists.add("//\t\t LOGGER.info(\"{}\",ids);");
        lists.add("//\t\t return " + filedServiceName + ".deleteById(ids);");
        lists.add("//} catch (Exception e) {");
        lists.add("//\t\t LOGGER.error(e.getMessage(), e);");
        lists.add("//\t\t return RpcResultBuilder.fail(Errors.Commons.DELETE_FAILED);");
        lists.add("//\t}");
        lists.add("//}");
        lists.add("}");

        write(lists, path + "admin/", name + ".java");

    }

    private void chooseService(String path, String className, String packageStr, String entityStr) throws IOException {
        if (StringUtils.isEmpty(packageStr)) {
            return;
        }
        List<String> lists = new ArrayList<String>();
        lists.add("package " + packageStr + ";");
//		lists.add("import com.fulihui.common.result.rpc.BaseResult;");
        lists.add("import com.baomidou.mybatisplus.extension.service.IService;");
//        lists.add("import com.github.pagehelper.Page;");
//        lists.add("import java.util.List;");
        lists.add("import " + entityStr + ";");
        lists.add("public interface " + serviceName + " extends IService<" + entityName + ">{");
//        lists.add("\t /**分页查询*/");
////		lists.add("\t List<" + entityName + "> selectLimitPage( " + entityName + " request);");
//        lists.add("\t Page<" + entityName + "> selectLimitPage( " + entityName + " request, Integer page, Integer pageLimit);");
//
//        lists.add("\t /**根据ID查询*/");
//        lists.add("\t " + entityName + " selectById( " + entityName + " request);");
//
//        lists.add("\t /**根据添加查询 */");
//        lists.add("\t List<" + entityName + "> selectEntity( " + entityName + " request);");
//
        lists.add("\t/**新增*/");
        lists.add("\t Integer insert(" + entityName + " request);");
//
//        lists.add("\t /**修改*/");
//        lists.add("\t int update(" + entityName + " request);");
//
//        lists.add("// \t /**修改状态*/");
//        lists.add("// \t int updateStatus(" + entityName + " request);");
//
//        lists.add("// \t/**删除*/");
//        lists.add("// \t int deleteById(List<Long> ids);");
        lists.add("}");
        write(lists, path, serviceName + ".java");
    }

    private void chooseAdminService(String path, String className) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.result.rpc.BaseResult;");
//		lists.add("import com.fulihui.common.result.rpc.SimpleResult;");

        lists.add("public interface " + adminServiceName + " {");
        lists.add("\t /**分页查询*/");
        lists.add("\t " + resultName + " selectLimitPage( " + requestName + " request);");

        lists.add("\t /**根据ID查询*/");
        lists.add("\t SimpleResult<" + dtoName + "> selectById( " + requestName + " request);");
        lists.add("\t /**根据动态条件查询 */");
        lists.add("\t SimpleResult<List<" + dtoName + ">> selectEntity( " + requestName + " request);");
        lists.add("\t/**新增*/");
        lists.add("\t BaseResult insert(" + requestName + " request);");

        lists.add("\t /**修改*/");
        lists.add("\t BaseResult update(" + requestName + " request);");

        lists.add("// \t /**修改状态*/");
        lists.add("// \t BaseResult updateStatus(" + requestName + " request);");

        lists.add("// \t/**删除*/");
        lists.add("// \t BaseResult deleteById(List<Long> ids);");
        lists.add("}");
        write(lists, path + "service/", adminServiceName + ".java");
    }

    private void chooseServiceImpl(String path, String serviceStr, String packageStr, String entityStr, String mapperStr) throws IOException {
        if (StringUtils.isEmpty(packageStr)) {
            return;
        }
        List<String> lists = new ArrayList<String>();
        String name = serviceName + "Impl";
        String repostioryName = formatFiledClass(mapperName);
        lists.add("package " + packageStr + ";");
//		lists.add("import org.springframework.stereotype.Component;");
//		lists.add("import com.alibaba.dubbo.config.annotation.Service;");
        lists.add("import org.springframework.beans.factory.annotation.Autowired;");
//		lists.add("import com.fulihui.common.result.rpc.BaseResult;");
//		lists.add("import com.fulihui.common.result.rpc.SimpleResult;");
//		lists.add("import java.util.ArrayList;");
//        lists.add("import java.util.List;");
        lists.add("import " + entityStr + ";");
        lists.add("import " + mapperStr + ";");
        lists.add("import " + serviceStr + ";");
//        lists.add("import com.github.pagehelper.Page;");
        lists.add("import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;");
//        lists.add("import com.github.pagehelper.PageHelper;");
        lists.add("import org.springframework.stereotype.Service;");


//		lists.add("import org.apache.commons.collections.CollectionUtils;");
//		lists.add("import org.springframework.beans.factory.annotation.Autowired;");
//		lists.add("import org.springframework.stereotype.Component;");
//		lists.add("import com.alibaba.dubbo.config.annotation.Service;");
//		lists.add("import com.fulihui.common.builder.rpc.RpcResultBuilder;");
//		lists.add("import com.fulihui.common.error.Errors;");

//		lists.add("@Component");
//		lists.add("@Service(interfaceClass = " + serviceName + ".class, version = \"1.0.0\")");
        lists.add("@Service");
        lists.add("public class " + name + " extends ServiceImpl<" + mapperName + "," + entityName + "> implements " + serviceName + "{");
        chooseServiceImpl(lists, repostioryName);
        lists.add("\t }");

        write(lists, path, name + ".java");
    }

    private void chooseAdminServiceImpl(String path) throws IOException {
        List<String> lists = new ArrayList<String>();
        String name = serviceName + "AdminImpl";
        String repostioryName = formatFiledClass(mapperName);
//		lists.add("import org.springframework.stereotype.Component;");
//		lists.add("import com.alibaba.dubbo.config.annotation.Service;");
        lists.add("import org.springframework.beans.factory.annotation.Autowired;");
//		lists.add("import com.fulihui.common.result.rpc.BaseResult;");
//		lists.add("import com.fulihui.common.result.rpc.SimpleResult;");
//		lists.add("import java.util.ArrayList;");
//		lists.add("import java.util.List;");
//		lists.add("import org.apache.commons.collections.CollectionUtils;");
//		lists.add("import org.springframework.beans.factory.annotation.Autowired;");
//		lists.add("import org.springframework.stereotype.Component;");
//		lists.add("import com.alibaba.dubbo.config.annotation.Service;");
//		lists.add("import com.fulihui.common.builder.rpc.RpcResultBuilder;");
//		lists.add("import com.fulihui.common.error.Errors;");

//		lists.add("@Component");
//		lists.add("@Service(interfaceClass = " + adminServiceName + ".class, version = \"1.0.0\")");
        lists.add("@Service");
        lists.add("public class " + name + " implements " + adminServiceName + "{");
        chooseServiceImpl(lists, repostioryName);

        write(lists, path + "service/", name + ".java");
    }

    private void chooseServiceImpl(List<String> lists, String repostioryName) {
        lists.add("\t @Autowired");
        lists.add("\t private " + mapperName + " " + repostioryName + ";");
//        lists.add("\t /**分页查询*/");
//        lists.add("\t  @Override");
//		lists.add("\t public List<" + entityName + "> selectLimitPage( " + entityName + " request){");
//		lists.add("\t\t  " + resultName + " pageResult = new " + resultName + "();");
////		lists.add("\t\t\t int page = null == request.getPage()?0:request.getPage();");
////		lists.add("\t\t\t int limit = null == request.getRows()?20:request.getRows();");
////		lists.add("\t\t\t " + entityName + " entity = getEntityByRequest(request);");
////		lists.add("\t\t\t entity.copy(request);");
//		lists.add("\t\t\t int count = " + repostioryName + ".selectCount(request);");
//		lists.add("\t\t\t if (count > 0) {");
//		lists.add("\t\t\t\t PageHelper.startPage(request.getPage(),  request.getRows(), false);");
//		lists.add("\t\t\t\t List<" + entityName + "> results = " + repostioryName + ".selectPageLimit(entity);");
////		lists.add("\t\t\t\t\t List<" + dtoName + "> lists = getDtosByEntitys(results);");
//		lists.add("\t\t\t\t\t pageResult.setValues(lists);");
//		lists.add("\t\t\t\t}");
//		lists.add("\t\t\t  pageResult.setPage(request.getPage());");
//		lists.add("\t\t\t  pageResult.setRows(request.getRows());");
//		lists.add("\t\t\t  pageResult.setTotalRows(count);");
//		lists.add("\t\t\t pageResult.setErrcode(TurnClientPageResult.SUCCESS);");
//		lists.add("\t\t\t return pageResult;");
//		lists.add("\t\t}");

//        lists.add("\t public Page<" + entityName + "> selectLimitPage( " + entityName + " request, Integer page, Integer pageLimit){");
//        lists.add("\t\t  PageHelper.startPage(page,pageLimit);");
//        lists.add("\t\t  Page<" + entityName + "> resultPage = " + repostioryName + ".selectPageLimit(request);");
//        lists.add("\t\t  return resultPage;");
//        lists.add("\t }");
//
//        String getIdMethod = getMethodNameMap.get(idFiled);
//
//        lists.add("\t/**根据ID查询*/");
//        lists.add("\t  @Override");
//        lists.add("\t public " + entityName + " selectById( " + entityName + " request){");
//        lists.add("\t\t " + entityName + " entity = " + repostioryName + ".selectEntityById(request."+getIdMethod+"());");
////		lists.add("\t\t "+dtoName+" taget = new "+dtoName+"();");
////		lists.add("\t\t return  RpcResultBuilder.succSimple(entity.copyDTO());");
//        lists.add("\t\t return  entity;");
//        lists.add("\t}");
//
//        lists.add("\t/**根据条件查询*/");
//        lists.add("\t  @Override");
//        lists.add("\t public List<" + entityName + "> selectEntity( " + entityName + " request){");
////		lists.add("\t     " + entityName + " entity = getEntityByRequest(request);");
//        lists.add("\t\t List<" + entityName + "> results = " + repostioryName + ".selectPageLimit(request);");
////		lists.add("\t\\t return getDtosByEntitys(results);");
//        lists.add("\t\t return results;");
//        lists.add("\t }");
//
        lists.add("\t/**新增*/");
        lists.add("\t  @Override");
        lists.add("\t public Integer insert(" + entityName + " entity){");
//		lists.add("\t\t " + entityName + " entity = getEntityByRequest(request);");
//		lists.add("\t\t entity.copy(request);");
//		lists.add("\t\t int count = " + repostioryName + ".insert(entity);");
        lists.add("\t\t int count = " + repostioryName + ".insertSelective(entity);");
//		lists.add("\t\t saveLogOfInsertOrDelete(entity,carExtensionWriteDTO.getOperator(),\"\");");
        lists.add("\t\t return count;");
//		lists.add(
//				"\t\t return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.SAVE_FAILED);");
        lists.add("\t}");
//
//        lists.add("\t /**修改*/");
//        lists.add("\t  @Override");
//        lists.add("\t public int update(" + entityName + " entity){");
////		lists.add("\t\t " + entityName + " entity = getEntityByRequest(request);");
////		lists.add("\t\t int count = " + repostioryName + ".updateByPrimaryKeySelective(entity);");
//        lists.add("\t\t return " + repostioryName + ".updateByExampleSelectiveById(entity);");
////		lists.add(
////				"\t\t return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);");
//        lists.add("\t}");
//
//        lists.add("//\t /**修改状态*/");
//        lists.add("//\t  @Override");
//        lists.add("//\t public int updateStatus(" + entityName + " entity){");
////		lists.add("//\t\t " + entityName + " entity = getEntityByRequest(request);");
//        lists.add("//\t\t return " + repostioryName + ".updateByExampleSelectiveById(entity);");
//        lists.add("//\t}");
//
//        lists.add("//\t/**删除*/");
//        lists.add("//\t  @Override");
//        lists.add("//\t public int deleteById(List<Long> ids){");
//        lists.add("//\t\t " + entityName + " entity = new " + entityName + "();");
////		lists.add("//\t\t entity.copy(request);");
//        lists.add("//\t}");


//		lists.add("\t/**校验参数对象不为空*/");
//		lists.add("\t public void checkParameter("+dtoName+" request){");
//		lists.add("\t\t  if (Objects.isNull(request)) {");
//		lists.add("\t\t\t throw new ParameterNullPointerException();");
//		lists.add("\t\t }");
//		lists.add("\t }");
//
//		lists.add("\t/**校验操作者不能为空*/");
//		lists.add("\t public void checkOperator("+dtoName+" request){");
//		lists.add("\t\t  if (StringUtils.isEmpty(request.getOperator())) {");
//		lists.add("\t\t\t throw new OperatorNullPointerException(JsonUtil.toJsonWithoutNull(request));");
//		lists.add("\t\t }");
//		lists.add("\t }");
//
//
//		for(String filed:fileds) {
//			String type = filedType.get(filed);
//			String getMethod = getMethodNameMap.get(filed);
//			String commend = filedComment.get(filed);
//
//			lists.add("\t/**校验'"+commend+"'不能为空*/");
//			lists.add("\t public void check"+StringUtils.substring(filed,0, 1).toUpperCase()+StringUtils.substring(filed, 1)+"("+dtoName+" request){");
//			if(Objects.equals("java.lang.String", type)) {
//				lists.add("\t\t  if (StringUtils.isEmpty(request."+getMethod+"())) {");
//			}else {
//				lists.add("\t\t  if (Objects.isNull(request."+getMethod+"())) {");
//			}
//
//			String errorText = "";
//			if(Objects.equals(filed.toLowerCase(), "isDelete".toLowerCase())) {
//				errorText = "StatusNullPointerException";
//			}
//
//
//			lists.add("\t\t\t throw new "+errorText+"(JsonUtil.toJsonWithoutNull(request));");
//			lists.add("\t\t }");
//			lists.add("\t }");
//		}
//
//
//		lists.add("\t /***判断是否是数字*/");
//		lists.add("\t private <O, T> void checkNumber(O value, String tipInfo, T t) {");
//		lists.add("\t\t  try {");
//		lists.add("\t\t\t  NumberUtils.createBigDecimal(value.toString());");
//		lists.add("\t\t  } catch (Exception e) {");
//		lists.add("\t\t\t  LOGGER.error(tipInfo, e);");
//		lists.add("\t\t\t throw new NumberCheckException(tipInfo + \";\" + JsonUtil.toJsonWithoutNull(t));");
//		lists.add("\t\t }");
//		lists.add("\t}");

//		lists.add("\t private " + entityName + " getEntityByRequest(" + entityName + " entity) {");
//		lists.add("\t 	 " + entityName + " entity = new " + entityName + "();");
//		lists.add("\t 	 entity.copy(request);");
//		lists.add("\t 	 return entity;");
//		lists.add("\t }");

//		lists.add("\t private List<" + dtoName + "> getDtosByEntitys(List<" + entityName + "> results){");
//		lists.add("\t     if(CollectionUtils.isEmpty(results)){");
//		lists.add("\t         return new ArrayList<" + dtoName + ">();");
//		lists.add("\t     }else{");
//		lists.add("\t        List<" + dtoName + "> lists = new ArrayList<" + dtoName + ">(results.size());");
//		lists.add("\t        results.forEach((source) -> {");
//		lists.add("\t             lists.add(source.copyDTO());");
//		lists.add("\t        });");
//		lists.add("\t        return lists;");
//		lists.add("\t    }");

//		lists.add("\t  private void saveLogOfInsertOrDelete("+entityName+" entity,String operator,String event,Integer count){");
//		lists.add("\t if(Objects.nonNull(count) && count.intValue() >0){");
//		lists.add("\t\t String desc = null;");
//		lists.add("\t\t try {");
//		lists.add("\t\t\t  desc = "+entityName+".getFiledAndDataDesc(entity);");
//		lists.add("\t\t\t if(StringUtils.isNotEmpty(desc)){");
//		lists.add("\t\t\t\t operateLogService.saveOperateLog(10,event,,desc,operator);");
//		lists.add("\t\t\t}");
//		lists.add("\t\t }catch (Exception e){");
//		lists.add("\t\t\t LOGGER.error(\"保存或删除    记录日志异常:[{}]\",desc,e);");
//		lists.add("\t\t\t Cat.logError(\"保存或删除    记录日志异常\"+desc,e);");
//		lists.add("\t\t}");
//		lists.add("\t}");
//		lists.add("\t}");
//
//
//		lists.add("\t  private void saveLogOfUpdate("+entityName+" oldEntity,"+entityName+" entity,String operator,String event,Integer count){");
//		lists.add("\t if(Objects.nonNull(count) && count.intValue() >0){");
//		lists.add("\t\t String content = null;");
//		lists.add("\t\t try {");
////		lists.add("\t\t\t content = "+entityName+".getFiledAndDataDesc(entity);");
//		lists.add("\t\t\t String desc = "+entityName+".toUpdateParameter(oldEntity,entity);");
//		lists.add("\t\t\t if(StringUtils.isNotEmpty(desc)){");
//		lists.add("\t\t\t\t operateLogService.saveOperateLog(10,event,,desc,operator);");
//		lists.add("\t\t\t }");
//		lists.add("\t\t }catch (Exception e){");
//		lists.add("\t\t\t LOGGER.error(\"修改    记录日志异常:[{}]\",content,e);");
//		lists.add("\t\t\t Cat.logError(\"修改    记录日志异常\"+content,e);");
//		lists.add("\t\t}");
//		lists.add("\t}");
//		lists.add("\t}");

//		lists.add("}");
    }

    private void chooseRepository(String path) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = formatFiledClass(entityName);
        lines.add("import org.springframework.stereotype.Repository;");
        lines.add("public interface " + repositoryName + " extends Mapper<" + entityName + "> {");
        lines.add("\t /**查询总条数*/");
        lines.add("\t int selectPageLimit_COUNT(" + entityName + " " + name + ");");
        lines.add("}");
        write(lines, path + "service/", repositoryName + ".java");
    }

    private void chooseMapper(String className, String path, String mapperName, String packageStr, String entityStr) throws IOException {
        String name = formatFiledClass(entityName);
        if (Objects.isNull(packageStr)) {
            return;
        }
        List<String> lines = new ArrayList<String>();
        lines.add("package " + packageStr + ";");
        lines.add("import org.apache.ibatis.annotations.Mapper;");
        lines.add("import com.baomidou.mybatisplus.core.mapper.BaseMapper;");
//        lines.add("import com.github.pagehelper.Page;");
//        lines.add("import java.util.List;");
        lines.add("import " + entityStr + ";");
        lines.add("@Mapper");
        lines.add("public interface " + mapperName + " extends BaseMapper<" + entityName + "> {");
//        lines.add("\t /**查询总条数*/");
//        lines.add("\t int selectPageLimit_COUNT(" + entityName + " " + name + ");");
//        lines.add("\t /**分页查询*/");
////		lines.add("\t List<" + entityName + "> selectPageLimit(" + entityName + " " + name + ");");
//        lines.add("\t Page<" + entityName + "> selectPageLimit(" + entityName + " " + name + ");");
//
//        lines.add("\t /**根据条件查询*/");
//        lines.add("\t List<" + entityName + "> selectEntity(" + entityName + " " + name + ");");
//
//        lines.add("\t /**根据ID查询*/");
//        lines.add("\t " + entityName + " selectEntityById(" + IdFiledType + " " + idFiled + ");");
//
////		lines.add("\t /**添加所有列  */");
////		lines.add("\t Integer insert(" + entityName + " " + name + ");");
        lines.add("\t /**插入有值的列  */");
        lines.add("\t Integer insertSelective(" + entityName + " " + name + ");");
//
////		lines.add("\t /**根据ID修改 所有列  */");
////		lines.add("\t Integer updateById(" + entityName + " " + name + ");");
//        lines.add("\t /**根据ID修改 非空的列  */");
//        lines.add("\t int updateByExampleSelectiveById(" + entityName + " " + name + ");");

//		lines.add("\t /**根据ID状态   */");
//		lines.add("\t Integer updateStatusById(" + entityName + " " + name + ");");
        lines.add("}");

        write(lines, path, mapperName + ".java");
    }

    private void chooseRequest(String path) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.util.DateUtils;");
        lists.add("public class " + requestName + " extends PageRequest implements java.io.Serializable{");
        lists.addAll(chooseFiled(false, false));
        lists.addAll(chooseEntityMethod(Boolean.FALSE));
        lists.addAll(chooseToString(true));

//		lists.add("}");
        write(lists, path, requestName + ".java");
    }

    private void choosePageResult(String path) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import com.fulihui.common.result.rpc.PageResult;");
        lists.add("import lombok.Getter;");
        lists.add("import lombok.Setter;");

        lists.add("@Getter");
        lists.add("@Setter");
        lists.add("public class " + resultName + " extends PageResult{");
        lists.add("\t private List<" + dtoName + "> values;");
        lists.add("}");
        write(lists, path, resultName + ".java");
    }

//	private void chooseMapper(String path,String className) throws IOException {
//		List<String> lines = new ArrayList<String>();
//		String mapper = className+"ExtMapper";
//		lines.add("import tk.mybatis.mapper.common.Mapper;");
//		lines.add("public interface "+mapper+" extends Mapper<"+entityName+"> {");
//		String name = formatFiledClass(entityName);
//		lines.add("\t /**查询总条数*/");
//		lines.add("\t int selectCount("+entityName+" "+ name+");");
//		lines.add("}");
//		
//		write(lines, path, mapper+".java");
//	}

    private void chooseMapperXML(String path, String className, String tableName, String entityStr, String mapperStr) throws IOException {
        List<String> lines = new ArrayList<String>();
        String name = StringUtils.substring(tableName, 0, 1).toUpperCase();
        int index = 0;

        lines.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        lines.add(
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
        lines.add("<mapper namespace=\"" + mapperStr + "\">");
        lines.add("\t <resultMap id=\"BaseResultMap\" type=\"" + entityStr + "\">");

        fileds.forEach((filed) -> {
            String column = columns.get(filed);
            String dbType = columnsType.get(column);
            if (column.equals(primaryKeyStr)) {
                this.idColumn = column.toUpperCase();
                this.idFiled = filed;
                this.idColumnDbType = dbType;
                IdFiledType = getJavaType(idColumnDbType);

                lines.add("\t\t <id column=\"" + column.toUpperCase() + "\" jdbcType=\"" + getDBType(dbType)
                        + "\" property=\"" + filed + "\" />");
            }

        });

        fileds.forEach((filed) -> {
            String column = columns.get(filed);
            String dbType = columnsType.get(column);
            if (column.equals(primaryKeyStr)) {

            } else {
                lines.add("\t\t  <result column=\"" + column.toUpperCase() + "\" jdbcType=\"" + getDBType(dbType)
                        + "\" property=\"" + filed + "\" />");
            }

        });
        lines.add("\t  </resultMap>");

        lines.addAll(chooseMapperXML("columns", columns, name));
        lines.add("");

//		lines.add("<insert id=\"insert\" keyColumn=\"" + idColumn + "\" keyProperty=\"" + idFiled
//				+ "\" useGeneratedKeys=\"true\" parameterType=\"\">");
//		lines.add("INSERT INTO " + tableName.toUpperCase() + " (<include refid= \"insert_columns\"></include>)");
//		lines.add("VALUES(<include refid= \"insert_values\"></include>)");
//		lines.add("</insert>");
//		lines.add("");

        lines.add("<insert id=\"insertSelective\" keyColumn=\"" + idColumn + "\" keyProperty=\"" + idFiled
                + "\" useGeneratedKeys=\"true\" parameterType=\"" + entityStr + "\">");
        lines.add("INSERT INTO " + tableName.toUpperCase() + " <include refid= \"insertSelectiveColumn\"></include>");
        lines.add("<include refid= \"insertSelectiveValue\"></include>");
        lines.add("</insert>");
        lines.add("");

//		lines.add(" <update id=\"updateById\" parameterType=\"\">");
//		lines.add("      UPDATE " + tableName.toUpperCase() + " SET ");
//		int size = fileds.size();
//
//		for (String filed : fileds) {
//			index++;
//			String column = columns.get(filed);
//			String dbType = columnsType.get(column);
//			if (column.equals(primaryKeyStr)) {
//				continue;
//			}
//
//			if (index == size) {
//				lines.add("\t\t" + column.toUpperCase() + "=#{" + filed + ",jdbcType=" + getDBType(dbType) + "}");
//			} else {
//				lines.add("\t\t" + column.toUpperCase() + "=#{" + filed + ",jdbcType=" + getDBType(dbType) + "},");
//			}
//		}
//
//		lines.add("      WHERE " + idColumn + "=#{" + idFiled + ",jdbcType=" + getDBType(idColumnDbType) + "}");
//		lines.add(" </update>");
//		lines.add("");

//        lines.add(" <update id=\"updateByExampleSelectiveById\" parameterType=\""+entityStr+"\">");
//        lines.add(" UPDATE " + tableName.toUpperCase());
//        lines.add("<include refid=\"updateByPrimaryKeySelectiveSql\"></include>");
//        lines.add("WHERE " + idColumn + "=#{" + idFiled + ",jdbcType=" + getDBType(idColumnDbType) + "}");
//        lines.add("</update>");
//        lines.add("");

//		lines.add(" <update id=\"updateStatusById\" parameterType=\"\">");
//		lines.add(" UPDATE " + tableName.toUpperCase());
//		lines.add(" SET ");
//		lines.add("WHERE " + idColumn + "=#{" + idFiled + ",jdbcType=" + getDBType(idColumnDbType) + "}");
//		lines.add("</update>");
//		lines.add("");

//        lines.add("<select id=\"selectPageLimit_COUNT\" resultType=\"java.lang.Integer\" parameterType=\""+entityStr+"\" >");
//        lines.add("SELECT COUNT(" + primaryKeyStr.toUpperCase() + ") FROM " + tableName.toUpperCase() + " " + name);
//        lines.add("WHERE 1=1  <include refid=\"where\"></include>");
//        lines.add("</select>");
//        lines.add("");
//
//        lines.add("<select id=\"selectPageLimit\" resultMap=\"BaseResultMap\" parameterType=\""+entityStr+"\">");
//        lines.add("SELECT <include refid=\"columns\"></include> FROM " + tableName.toUpperCase() + " " + name
//                + " WHERE 1=1 ");
//        lines.add("<include refid=\"where\"></include>");
//        lines.add("</select>");
//        lines.add("");
//
//        lines.add("<select id=\"selectEntity\" resultMap=\"BaseResultMap\" parameterType=\""+entityStr+"\">");
//        lines.add("SELECT <include refid=\"columns\"></include> FROM " + tableName.toUpperCase() + " " + name
//                + " WHERE 1=1 ");
//        lines.add("<include refid=\"where\"></include>");
//        lines.add("</select>");
//        lines.add("");

//        lines.add("<select id=\"selectEntityById\" resultMap=\"BaseResultMap\" parameterType=\"" + IdFiledType + "\">");
//        lines.add("SELECT <include refid=\"columns\"></include> FROM " + tableName.toUpperCase() + " " + name
//                + " WHERE ");
//        lines.add(idColumn + "=#{" + idFiled + ",jdbcType=" + getDBType(idColumnDbType) + "}");
//        lines.add("</select>");
//        lines.add("");

//		lines.add("<sql id=\"insert_columns\">");
//		lines.addAll(chooseMapperXML("columns", columns,name));
//		lines.add("</sql>");
        lines.add("");
        lines.add("");
        lines.add("");

        lines.addAll(chooseMapperXML("insert_columns", columns, null, fileds));
        lines.addAll(chooseAddFiled("insert_values", fileds));
        lines.add("");

        lines.add("<sql id=\"insertSelectiveColumn\">");
        lines.add(" <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
        fileds.forEach((filed) -> {
            String column = columns.get(filed).toUpperCase();
            lines.add("<if test=\"null!=" + filed + "\">");
            lines.add("  " + column + ",");
            lines.add("</if>");
        });
        lines.add("</trim>");
        lines.add("</sql>");
        lines.add("");

        lines.add("<sql id=\"insertSelectiveValue\">");
        lines.add("  <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">");
        fileds.forEach((filed) -> {
            String column = columns.get(filed);
            String dbType = columnsType.get(column);
            lines.add("<if test=\"null!=" + filed + "\">");
            lines.add("  #{" + filed + ",jdbcType=" + getDBType(dbType) + "},");
            lines.add("</if>");
        });
        lines.add("</trim>");
        lines.add("</sql>");
        lines.add("");

        lines.add("<sql id=\"updateByPrimaryKeySelectiveSql\">");
        lines.add(" <set>");
        fileds.forEach((filed) -> {
            String column = columns.get(filed);
            String dbType = columnsType.get(column);
            if (column.equals(primaryKeyStr)) {

            } else {
                lines.add("<if test=\"null!=" + filed + "\">");
                lines.add("  " + column.toUpperCase() + "=#{" + filed + ",jdbcType=" + getDBType(dbType) + "},");
                lines.add("</if>");
            }
        });
        lines.add("</set>");
        lines.add("</sql>");
        lines.add("");

        lines.add("<sql id=\"where\">");
        fileds.forEach((filed) -> {
            String column = columns.get(filed);
            String dbType = columnsType.get(column);
            lines.add("<if test=\"null!=" + filed + "\">");
            lines.add(" AND " + name + "." + column.toUpperCase() + "=#{" + filed + ",jdbcType=" + getDBType(dbType)
                    + "}");
            lines.add("</if>");
        });
        lines.add("</sql>");

        lines.add("</mapper>");

        write(lines, path, className + "Mapper.xml");

    }

    private List<String> chooseMapperXML(String id, Map<String, String> maps, String name) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t <sql id=\"" + id + "\">");
        StringBuilder builder = new StringBuilder();
        maps.forEach((k, v) -> {
            if (!"".equals(builder.toString())) {
                builder.append(",");
            }
            if (StringUtils.isNotEmpty(name)) {
                builder.append(name);
                builder.append(".");
            }
            builder.append(v.toUpperCase());
        });
        lists.add("\t\t" + builder.toString());
        lists.add("\t </sql>");
        return lists;
    }

    private List<String> chooseMapperXML(String id, Map<String, String> maps, String name, List<String> files) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t <sql id=\"" + id + "\">");
        StringBuilder builder = new StringBuilder();
        files.forEach((f) -> {
            if (!"".equals(builder.toString())) {
                builder.append(",");
            }
            if (StringUtils.isNotEmpty(name)) {
                builder.append(name);
                builder.append(".");
            }
            builder.append(maps.get(f).toUpperCase());
        });

        lists.add("\t\t" + builder.toString());
        lists.add("\t </sql>");
        return lists;
    }

    private List<String> chooseAddFiled(String id, List<String> files) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t <sql id=\"" + id + "\">");
        StringBuilder builder = new StringBuilder();
        files.forEach((v) -> {
            if (!"".equals(builder.toString())) {
                builder.append(",");
            }
            builder.append("#{");
            builder.append(v);
            builder.append("}");
        });
        lists.add("\t\t" + builder.toString());
        lists.add("\t </sql>");
        return lists;
    }

    private void chooseEntityVO(String className, String path, String packageStr, String entityStr) throws IOException {
        List<String> lists = new ArrayList<String>();
//		String name = className+"VO";
//		lists.add("import com.fulihui.common.util.DateUtils;");
//		lists.add("\r\n@ApiModel(value=\"" + voName + "对象\",description=\"\")");
        lists.add("package " + packageStr + ";");
        lists.add("import com.alibaba.fastjson.JSON;");
        lists.add("import io.swagger.annotations.ApiModel;");
        lists.add("import io.swagger.annotations.ApiModelProperty;");
//        lists.add("import lombok.Data;");

        lists.add("@ApiModel");
//        lists.add("@Data");
        lists.add("public class " + voName + " implements java.io.Serializable{");
        Long value = RandomUtils.nextLong();
        lists.add(" private static final long serialVersionUID = " + value + "L;");
        lists.addAll(chooseFiledVo());
        lists.addAll(chooseEntityMethod(Boolean.FALSE));

//		lists.addAll(chooseVoCopy("void", "source", dtoName));
//		lists.addAll(chooseCopyPropertiesVO("source", voName));
//		lists.addAll(chooseToString(false));
        lists.add("\t @Override");
        lists.add("\t  public String toString() {return JSON.toJSONString(this);}");

        lists.add("}");
        write(lists, path, voName + ".java");
    }

    private List<String> chooseCopyPropertiesVO(String sourceName, String className) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t/**");
        lists.add("\t  @param preperties需要copy的字段集合");
        lists.add("\t */");
        lists.add("\t public " + className + " copyPreperties(" + dtoName + " " + sourceName
                + ",String ...preperties) {");
        lists.add("\t\t if(ArrayUtils.isEmpty(preperties)){");
        lists.add("\t\t\t return null;");
        lists.add("\t\t }");
        lists.add("\t\t\t " + className + " target = new " + className + "();");
        CopyProperties(sourceName, lists);
        lists.add("\t\t return target;");
        lists.add("}");
        return lists;
    }

    private List<String> chooseVoCopy(String className, String sourceName, String sourClass) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t\t public " + className + " copy(" + sourClass + " " + sourceName + ") {");
        copy(sourceName, lists, "this");
        lists.add("\t }");
        return lists;
    }

    private void chooseEntityDto(String className, String path, String packageStr, String entityStr, boolean dto) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import lombok.Data;");
        lists.add("package " + packageStr + ";");
        lists.add("import com.alibaba.fastjson.JSON;");
        lists.add("import javax.validation.constraints.NotEmpty;");
        lists.add("import io.swagger.annotations.ApiModel;");
        lists.add("import io.swagger.annotations.ApiModelProperty;");
//        lists.add("import lombok.Data;");
        lists.add("@ApiModel");
//        lists.add("@Data");
        lists.add("public class " + className + " implements java.io.Serializable{");
        Long value = RandomUtils.nextLong();
        lists.add(" private static final long serialVersionUID = " + value + "L;");
        lists.addAll(chooseFiled(Objects.equals(className, updateDTO), dto));

        lists.addAll(chooseEntityMethod(Boolean.TRUE));

//		lists.addAll(chooseToString(false));
        lists.add("\t @Override");
        lists.add("\t  public String toString() {return JSON.toJSONString(this);}");
        lists.add("}");
        write(lists, path, className + ".java");

    }

    private void chooseUpdateQueryDto(String className, String path, String packageStr, String entityStr) throws IOException {
        List<String> lists = new ArrayList<String>();
//		lists.add("import lombok.Data;");
        lists.add("package " + packageStr + ";");
        lists.add("import com.alibaba.fastjson.JSON;");
        lists.add("import javax.validation.constraints.NotEmpty;");
        lists.add("import io.swagger.annotations.ApiModel;");
        lists.add("import io.swagger.annotations.ApiModelProperty;");
//        lists.add("import lombok.Data;");
        lists.add("@ApiModel");
//        lists.add("@Data");
        lists.add("public class " + className + " implements java.io.Serializable{");
        Long value = RandomUtils.nextLong();
        lists.add(" private static final long serialVersionUID = " + value + "L;");
        lists.addAll(chooseFiledVo());
        lists.addAll(chooseEntityMethod(Boolean.TRUE));

//		lists.addAll(chooseToString(false));
        lists.add("\t @Override");
        lists.add("\t  public String toString() {return JSON.toJSONString(this);}");
        lists.add("}");
        write(lists, path, className + ".java");

    }

    private void chooseUpdateStatusDto(String className, String path, String packageStr, String entityStr) throws IOException {
        boolean flag = Boolean.FALSE;

        Set<String> sets = fileds.stream().filter((filed) -> {
            String javaType = filedType.get(filed);
            return Objects.equals(javaType, "java.lang.Boolean");
        }).collect(Collectors.toSet());

        if (Objects.isNull(sets) || sets.size() == 0) {
            return;
        }

        List<String> lists = new ArrayList<String>();
//		lists.add("import lombok.Data;");
        lists.add("package " + packageStr + ";");
        lists.add("import com.alibaba.fastjson.JSON;");
        lists.add("import javax.validation.constraints.NotEmpty;");
        lists.add("import io.swagger.annotations.ApiModel;");
        lists.add("import io.swagger.annotations.ApiModelProperty;");
//        lists.add("import lombok.Data;");
        lists.add("@ApiModel");
//        lists.add("@Data");
        lists.add("public class " + className + " implements java.io.Serializable{");
        Long value = RandomUtils.nextLong();
        lists.add(" private static final long serialVersionUID = " + value + "L;");

        lists.addAll(chooseUpdateStatusFiled());

//		lists.addAll(chooseToString(false));
        lists.add("\t @Override");
        lists.add("\t  public String toString() {return JSON.toJSONString(this);}");
        lists.add("}");
        write(lists, path, className + ".java");

    }


    private List<String> chooseUpdateStatusFiled() {
        List<String> lists = new ArrayList<String>();
        chooseUpdateStatusList(lists, idFiled);
        chooseUpdateStatusList(lists, "operator");

        fileds.forEach((filed) -> {
            String javaType = filedType.get(filed);
            if (Objects.equals(javaType, "java.lang.Boolean")) {
                chooseUpdateStatusList(lists, filed);
            }
        });

        chooseEntityMethod(lists, idFiled);
        chooseEntityMethod(lists, "operator");
        fileds.forEach((filed) -> {
            String javaType = filedType.get(filed);
            if (Objects.equals(javaType, "java.lang.Boolean")) {
                chooseEntityMethod(lists, filed);
            }
        });

        return lists;
    }

    private void chooseUpdateStatusList(List<String> lists, String filed) {
        String javaType = filedType.get(filed);
        String comment = filedComment.get(filed);
        Integer len = filedLength.get(filed);
        String modelProperty = "@ApiModelProperty(value=\"" + comment + "\",required = true)";
        if (ArrayUtils.contains(nums, javaType)) {
            modelProperty = "@ApiModelProperty(value=\"" + comment + "\",example =\"1\",required = true)";
        }
        lists.add("\t /**" + comment + "*/");
        lists.add("\t  " + modelProperty);
//            if(isValidation) {
        lists.add("\t @NotEmpty(message = \"『" + comment + "』  不能为空\")");
//            }
        if (Objects.nonNull(len)) {

        }
        lists.add("\t private " + javaType + " " + filed + ";");


    }

    private List<String> chooseFiled(boolean idNotNULL, boolean dto) {
        List<String> lists = new ArrayList<String>();
        fileds.forEach((filed) -> {
            if (dto && switchDTO(filed)) {
                return;
            }
            String javaType = filedType.get(filed);
            String comment = filedComment.get(filed);
            Integer len = filedLength.get(filed);
            String modelProperty = "@ApiModelProperty(value=\"" + comment + "\",required = true)";
            if (!idNotNULL && Objects.equals(filed, idFiled)) {
                modelProperty = "@ApiModelProperty(value=\"" + comment + "\")";
            }
            if (ArrayUtils.contains(nums, javaType)) {
                modelProperty = "@ApiModelProperty(value=\"" + comment + "\",example =\"1\",required = true)";
                if (!idNotNULL && Objects.equals(filed, idFiled)) {
                    modelProperty = "@ApiModelProperty(value=\"" + comment + "\",example =\"1\")";
                }
            }


            lists.add("\t /**" + comment + "*/");
            lists.add("\t  " + modelProperty);
//            if(isValidation) {
            lists.add("\t @NotEmpty(message = \"『" + comment + "』  不能为空\")");
//            }
            if (Objects.nonNull(len)) {

            }
            lists.add("\t private " + javaType + " " + filed + ";");
        });


        return lists;
    }

    private List<String> chooseFiledVo() {
        List<String> lists = new ArrayList<String>();
        fileds.forEach((filed) -> {
            String javaType = filedType.get(filed);
            String comment = filedComment.get(filed);

            String modelProperty = "@ApiModelProperty(\"" + comment + "\")";
            if (ArrayUtils.contains(nums, javaType)) {
                modelProperty = "@ApiModelProperty(value=\"" + comment + "\",example =\"1\")";
            }

            lists.add("\t /**" + comment + "*/");
            lists.add("\t  " + modelProperty);
            lists.add("\t private " + javaType + " " + filed + ";");
        });

        return lists;
    }

    private void chooseEntity(List<Map<String, String>> data, String table, String className, String path, String packageStr)
            throws IOException {
        List<String> lists = new ArrayList<String>();

        lists.add("package " + packageStr + ";");
        lists.add("import lombok.Data;");
        lists.add("import com.baomidou.mybatisplus.annotation.IdType;");
        lists.add("import com.baomidou.mybatisplus.annotation.TableField;");
        lists.add("import com.baomidou.mybatisplus.annotation.TableId;");
        lists.add("import com.baomidou.mybatisplus.annotation.TableName;");
        lists.add("import org.apache.commons.lang3.StringUtils;");
//        lists.add("import io.swagger.annotations.ApiModel;");
        lists.add("import lombok.EqualsAndHashCode;");
        lists.add("import lombok.experimental.Accessors;");
        lists.add("import lombok.extern.slf4j.Slf4j;");
//        lists.add("import java.util.Objects;");


//		lists.add("@Table(name = \"" + table + "\")");
        lists.add("@TableName(\"" + table + "\")");

        entityName = className + "Entity";

        lists.add("@Data");
        lists.add("@Slf4j");
        lists.add("@Accessors(chain = true)");
        lists.add("@EqualsAndHashCode(callSuper = false)");
        lists.add("public class " + entityName + "{");
        if (Objects.equals(table, "db_fhdb")) {
            System.out.println("1");
        }
        lists.addAll(chooseEntityFiled(data));
        chooseEntityMethod(Boolean.FALSE);
//		lists.addAll(chooseEntityMethod());
//		lists.addAll(chooseCopy("this"));
//		lists.addAll(chooseCopyProperties("this"));
//		lists.addAll(chooseCopyOther(dtoName));
//		lists.addAll(chooseCopyPropertiesOther(dtoName));
//		lists.addAll(chooseVoCopy("void", "request", requestName));
//        lists.addAll(chooseEntityToUpdate());
//        lists.addAll(chooseCreateObj(entityName));
        lists.addAll(chooseToString(false));
        lists.add("}");
        if (StringUtils.isEmpty(packageStr)) {
            return;
        }
        write(lists, path, entityName + ".java");

    }

    private List<String> chooseCreateObj(String objName) {
        List<String> lines = new ArrayList<String>();
        lines.add("\t/**");
        fileds.forEach((field) -> {
            String common = filedComment.get(field);
            lines.add("\t *  @param " + field + " " + common);
        });
        lines.add("\t */");
        StringBuilder params = new StringBuilder();
        params.append(" public static " + objName + " createObj(");

        fileds.forEach((filed) -> {
            String type = filedType.get(filed);
            params.append(type);
            params.append(" ");
            params.append(filed);
            params.append(",");

        });

        lines.add(StringUtils.substringBeforeLast(params.toString(), ",") + "){");
        lines.add("\t\t " + objName + " obj = new " + objName + "();");
        fileds.forEach((filed) -> {
            String setMethod = setMethodNameMap.get(filed);

            lines.add("\t\t obj." + setMethod + "(" + filed + ");");
        });
        lines.add("\t return obj;");
        lines.add("}");
        return lines;
    }

    private List<String> chooseEntityToUpdate() {
        List<String> lines = new ArrayList<String>();
//        lines.add("\t private void chooseTOUpdate(Object value1,Object value2,String filed,StringBuilder build) {");
//        lines.add("\t\t  if(null == value1 && null == value2) {");
//        lines.add("\t\t\t return;");
//        lines.add("\t\t  }else if(null == value1 || null == value2) {");
//        lines.add("\t\t\t combinationCharacter(filed, value2, build);");
//        lines.add("\t\t }else if(!value1.equals(value2)) {");
//        lines.add("\t\t\t combinationCharacter(filed, value2, build);");
//        lines.add("\t\t}");
//        lines.add("\t}");

//        lines.add("\t private String toUpdate(" + entityName + " source){");
//        lines.add("\t\t StringBuilder build = new StringBuilder();");
//        fileds.forEach((filed) -> {
//            String getMethod = getMethodNameMap.get(filed);
//            lines.add("\t\t chooseTOUpdate(this." + getMethod + "(),source." + getMethod + "(),\"" + filed
//                    + "\",build);");
//        });
//        lines.add("\t return StringUtils.isEmpty(build.toString())?null:\"{\"+build.toString()+\"}\";");
//        lines.add("}");

        return lines;
    }

    private List<String> chooseEntityFiled(List<Map<String, String>> data) {
        List<String> lists = new ArrayList<String>();
        data.forEach((map) -> {
            String column = map.get("COLUMN_NAME");
            String type = map.get("DATA_TYPE").toLowerCase();
            Integer length = getLength(map.get("CHARACTER_MAXIMUM_LENGTH"), map.get("NUMERIC_PRECISION"), map.get("numeric_scale"));
            String comment = map.get("COLUMN_COMMENT");
            String javaType = getJavaType(type);

            String filed = getFiled(column);


            fileds.add(filed);
            columns.put(filed, column);
            columnsType.put(column, type);
            filedLength.put(filed, length);
            columnsComment.put(column, comment);
            filedComment.put(filed, comment);
            filedType.put(filed, javaType);

//			String formatName = format(filed, null);

            String formatName = StringUtils.substring(filed, 0, 1).toUpperCase();
            if (StringUtils.length(filed) > 1) {
                formatName = formatName + StringUtils.substring(filed, 1);
            }

            String getMethodName = "get" + formatName;
            String setMethodName = "set" + formatName;

            getMethodNameMap.put(filed, getMethodName);
            setMethodNameMap.put(filed, setMethodName);

            lists.add("");
            lists.add("\t /**" + comment + "*/");

            if (column.equals(primaryKeyStr)) {

                lists.add("\t @TableId(value = \"" + column + "\", type = IdType.AUTO)");
            } else {
                lists.add("\t  @TableField(\"" + column + "\")");
            }

            lists.add("\t private " + javaType + " " + filed + ";");
        });
        lists.add("");
        lists.add("");
        lists.add("");
        lists.add("");
        lists.add("");
        lists.add("private final static java.util.Set<String> DATE_FILES = new java.util.HashSet<>();");
        lists.add("{");
        for (String filed : fileds) {
            String type = filedType.get(filed);
            if (Objects.equals("java.util.Date", type.trim())) {
                lists.add("\t\t DATE_FILES.add(\"" + filed + "\");");
            } else if (Objects.equals("java.time.LocalDateTime", type)) {
                lists.add("\t\t DATE_FILES.add(\"" + filed + "\");");
            }
        }
        lists.add("}");

        lists.add("\t private final static java.util.Map<String,String> FILE_DESC_MAP = new java.util.HashMap(" + columnsComment.size() + ");");
        lists.add("\t{");
        for (String filed : fileds) {
            String commend = filedComment.get(filed);
            lists.add("\t\t FILE_DESC_MAP.put(\"" + filed + "\",\"" + commend + "\");");
        }
        lists.add("\t}");


        lists.add("\t private final static java.util.Map<String,String> FILE_COLUMNS_MAP = new java.util.HashMap(" + columnsComment.size() + ");");
        lists.add("\t{");
        for (String filed : fileds) {
            String column = columns.get(filed);
            lists.add("\t\t FILE_COLUMNS_MAP.put(\"" + filed + "\",\"" + column + "\");");
        }
        lists.add("\t}");




        if (!Objects.equals("1", entity.getIsDateType()))  {
            lists.add("\t\t private static final java.time.format.DateTimeFormatter DATE_TIME_FORMATTER = java.time.format.DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\");");
            lists.add("\t private void jsonArrayAddStrOfLocalDateTime(String commend, com.google.gson.JsonArray jsonArray, java.time.LocalDateTime value){");
            lists.add("\t\t  if(java.util.Objects.isNull(value)){");
            lists.add("\t\t\t return;");
            lists.add("\t\t }");
            lists.add("\t\t jsonArrayAddStr(commend,DATE_TIME_FORMATTER.format(value),jsonArray);");
            lists.add("\t}");


            lists.add("\t  private void jsonArrayUpdateOfLocalDateTime(String commend, java.time.LocalDateTime newValue, java.time.LocalDateTime oldValue, com.google.gson.JsonArray jsonArray){");

            lists.add("\t\t String newDateStr = java.util.Objects.isNull(newValue)?null:DATE_TIME_FORMATTER.format(newValue);");
            lists.add("\t\t String oldDateStr = java.util.Objects.isNull(oldValue)?null:DATE_TIME_FORMATTER.format(oldValue);");
            lists.add("\t\t jsonArrayUpdate(commend, newDateStr, oldDateStr, jsonArray);");
            lists.add("\t}");
        } else {
            lists.add("\t private void jsonArrayAddStrOfDate(String commend, java.util.Date value, com.google.gson.JsonArray jsonArray){");
            lists.add("\t\t  if(java.util.Objects.isNull(value)){");
            lists.add("\t\t\t return;");
            lists.add("\t\t }");

            lists.add("\t\t jsonArrayAddStr(commend," + entity.getDateUtils() + ".format(value),jsonArray);");
            lists.add("\t}");


            lists.add("\t  private void jsonArrayUpdateOfDate(String commend, java.util.Date newValue, java.util.Date oldValue, com.google.gson.JsonArray jsonArray){");

            lists.add("\t\t String newDateStr = java.util.Objects.isNull(newValue)?null:" + entity.getDateUtils() + ".format(newValue);");
            lists.add("\t\t String oldDateStr = java.util.Objects.isNull(oldValue)?null:" + entity.getDateUtils() + ".format(oldValue);");
            lists.add("\t\t jsonArrayUpdate(commend, newDateStr, oldDateStr, jsonArray);");
            lists.add("\t}");
        }

        lists.add("\t private <T>void jsonArrayAddStr(String commend,T value,com.google.gson.JsonArray jsonArray){");
        lists.add("\t\t   boolean flag = java.util.Optional.ofNullable(value).map(val -> {");
        lists.add("\t\t\t return org.apache.commons.lang3.StringUtils.isNotEmpty(val.toString());");
        lists.add("\t\t}).orElse(Boolean.FALSE);");
        lists.add("\t\t  if (flag && org.apache.commons.lang3.StringUtils.isNotEmpty(commend)) {");
        lists.add("\t\t\t  jsonArray.add(commend + \":『\" + value + \"』\");");
        lists.add("\t\t }");
        lists.add("\t }");

        lists.add("\t  private <T> void jsonArrayUpdate(String commend, T newValue, T oldValue, com.google.gson.JsonArray jsonArray){");
        lists.add("\t\t  boolean flag = java.util.Optional.ofNullable(newValue).map(value -> {");
        lists.add("\t\t\t  return org.apache.commons.lang3.StringUtils.isNotEmpty(value.toString()) && !java.util.Objects.equals(value, oldValue);");
        lists.add("\t\t   }).orElse(Boolean.FALSE);");
        lists.add("\t  if (flag && org.apache.commons.lang3.StringUtils.isNotEmpty(commend)) {");
        lists.add("\t\t  Object value = java.util.Objects.isNull(oldValue)?\"\":oldValue;");
        lists.add("\t\t  StringBuilder builder = new StringBuilder();");
        lists.add("\t\t\t builder.append(commend+\":从 『\").append(value).append(\"』修改为『\").append(newValue).append(\"』\");");
        lists.add("\t\t\t jsonArray.add(builder.toString());");
        lists.add("\t\t}");
        lists.add("\t}");


        lists.add("\t /***获取实体的值*/");
        lists.add("\t private <T> T getResult(String fieldName, " + entityName + " entity) {");
        lists.add("\t\t try {");
        lists.add("\t\t\t   Class<?> aClass = entity.getClass();");
        lists.add("\t\t\t  java.beans.BeanInfo beanInfo = java.beans.Introspector.getBeanInfo(aClass); ");
        lists.add("\t\t\t  java.util.Optional<java.beans.PropertyDescriptor> optional = java.util.Arrays.stream(beanInfo.getPropertyDescriptors()).filter(p -> { ");
        lists.add("\t\t\t\t  return java.util.Objects.equals(p.getName(), fieldName); ");
        lists.add("\t\t\t  }).findFirst(); ");
        lists.add("\t\t\t  return optional.isPresent() ? (T) optional.get().getReadMethod().invoke(entity) : null; ");
        lists.add("\t\t  } catch (java.beans.IntrospectionException e) {");
        lists.add("\t\t\t log.error(\"读属性取值异常:[{}][{}]\", fieldName, e.getMessage(), e);");
        lists.add("\t\t  } catch (java.lang.IllegalAccessException e) {");
        lists.add("\t\t\t log.error(\"读属性取值异常:[{}][{}]\", fieldName, e.getMessage(), e);");
        lists.add("\t\t  } catch (java.lang.reflect.InvocationTargetException e) {");
        lists.add("\t\t\t log.error(\"读属性取值异常:[{}][{}]\", fieldName, e.getMessage(), e);");
        lists.add("\t\t}");
        lists.add("\t\t return null;");
        lists.add("\t }");

        lists.add("\t /**数据描述*/");
        lists.add("public  String toFiledAndDataDesc(){");

        lists.add("\t\t com.google.gson.JsonArray jsonArray = new com.google.gson.JsonArray(FILE_DESC_MAP.size());");
        lists.add("\t\t\t FILE_DESC_MAP.forEach((key, val) -> {");
        lists.add("\t\t\t\t if (DATE_FILES.contains(key)) {");
        if (!Objects.equals("1", entity.getIsDateType())) {
            lists.add("\t\t\t\t\t jsonArrayAddStrOfLocalDateTime(val,jsonArray, getResult(key, this));");
        } else {
            lists.add("\t\t\t\t\t jsonArrayAddStrOfDate(val, getResult(key, this), jsonArray);");
        }
        lists.add("\t\t\t\t  } else {");
        lists.add("\t\t\t\t\t  jsonArrayAddStr(val, getResult(key, this), jsonArray);");
        lists.add("\t\t\t\t }");
        lists.add("\t\t\t });");

        lists.add("\t\t   return jsonArray.size()== 0?\"\":jsonArray.toString();");
        lists.add("\t }");


        lists.add("\t /**数据描述*/");
        lists.add("public String toColumnsDataDesc(){");
        lists.add("\t\t com.google.gson.JsonArray jsonArray = new com.google.gson.JsonArray(FILE_DESC_MAP.size());");
        lists.add("\t\t\t FILE_DESC_MAP.forEach((key, val) -> {");
        lists.add("\t\t\t\t if (DATE_FILES.contains(key)) {");
        if (!Objects.equals("1", entity.getIsDateType()))  {
            lists.add("\t\t\t\t\t jsonArrayAddStrOfLocalDateTime(FILE_COLUMNS_MAP.get(key),jsonArray, getResult(key, this));");
        } else {
            lists.add("\t\t\t\t\t jsonArrayAddStrOfDate(FILE_COLUMNS_MAP.get(key), getResult(key, this), jsonArray);");
        }

        lists.add("\t\t\t\t  } else {");
        lists.add("\t\t\t\t\t  jsonArrayAddStr(FILE_COLUMNS_MAP.get(key), getResult(key, this), jsonArray);");
        lists.add("\t\t\t\t }");
        lists.add("\t\t\t });");


        lists.add("\t\t   return jsonArray.size()== 0?\"\":jsonArray.toString();");
        lists.add("\t }");

        lists.add("\t /**数据修改值描述（字段说明）*/");
        lists.add("\t public String toUpdateParameter(" + entityName + " oldEntity){");
        lists.add("\t\t com.google.gson.JsonArray jsonArray = new com.google.gson.JsonArray(FILE_DESC_MAP.size());");
        lists.add("\t\t if (java.util.Objects.isNull(oldEntity)) { return \"\";}");

        lists.add("\t\t\t FILE_DESC_MAP.forEach((key, val) -> {");
        lists.add("\t\t\t\t if (DATE_FILES.contains(key)) {");
        if (!Objects.equals("1", entity.getIsDateType())) {
            lists.add("\t\t\t\t\t jsonArrayUpdateOfLocalDateTime(val, getResult(key, this), getResult(key, oldEntity), jsonArray);");
        } else {
            lists.add("\t\t\t\t\t  jsonArrayUpdateOfDate(val, getResult(key, this), getResult(key, oldEntity), jsonArray);");
        }

        lists.add("\t\t\t\t  } else {");
        lists.add("\t\t\t\t\t  jsonArrayUpdate(val, getResult(key, this), getResult(key, oldEntity), jsonArray);");
        lists.add("\t\t\t\t }");
        lists.add("\t\t\t });");

        lists.add("\t\t   return jsonArray.size()== 0?\"\":jsonArray.toString();");
        lists.add("\t }");


        lists.add("\t /**数据修改值描述（列名）*/");
        lists.add("public String toColumnsUpdateDataDesc(" + entityName + " oldEntity){");
        lists.add("\t\t if (java.util.Objects.isNull(oldEntity)) { return \"\";}");
        lists.add("\t\t com.google.gson.JsonArray jsonArray = new com.google.gson.JsonArray(FILE_DESC_MAP.size());");
        lists.add("\t\t\t FILE_DESC_MAP.forEach((key, val) -> {");
        lists.add("\t\t\t\t if (DATE_FILES.contains(key)) {");
        if (!Objects.equals("1", entity.getIsDateType()))  {
            lists.add("\t\t\t\t\t jsonArrayUpdateOfLocalDateTime(FILE_COLUMNS_MAP.get(key), getResult(key, this), getResult(key, oldEntity), jsonArray);");
        } else {
            lists.add("\t\t\t\t\t  jsonArrayUpdateOfDate(FILE_COLUMNS_MAP.get(key), getResult(key, this), getResult(key, oldEntity), jsonArray);");
        }

        lists.add("\t\t\t\t  } else {");
        lists.add("\t\t\t\t\t  jsonArrayUpdate(FILE_COLUMNS_MAP.get(key), getResult(key, this), getResult(key, oldEntity), jsonArray);");
        lists.add("\t\t\t\t }");
        lists.add("\t\t\t });");

        lists.add("\t\t   return jsonArray.size()== 0?\"\":jsonArray.toString();");
        lists.add("\t }");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(entity.getJsonConvertMethod())) {
            lists.add("\t @Override");
            lists.add("\t public String toString() { return " + entity.getJsonConvertMethod() + "(this);}");
        }

        return lists;
    }

    private void chooseEntityMethod(List<String> lists, String key) {
        String value = getMethodNameMap.get(key);
        String comment = filedComment.get(key);
        String type = filedType.get(key);
        String setMethodName = setMethodNameMap.get(key);

        lists.add("");
        lists.add("");

        lists.add("\t/**" + comment + "*/");
        lists.add("\t public " + type + " " + value + "(){");
        lists.add("\t\t return this." + key + ";");
        lists.add("\t}");


        lists.add("");
        lists.add("");

        lists.add("\t/**" + comment + "*/");
        lists.add("\t public void " + setMethodName + "(" + type + " " + key + "){");
        lists.add("\t\t this." + key + "= " + key + ";");
        lists.add("\t}");

    }

    private List<String> chooseEntityMethod(final boolean dto) {
        List<String> lists = new ArrayList<String>();

        getMethodNameMap.forEach((key, value) -> {
            if (dto && switchDTO(key)) {
                return;
            }
            chooseEntityMethod(lists, key);
        });

        return lists;
    }

    private List<String> chooseCopyOther(String targetName) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t public " + targetName + " copyDTO() {");
        lists.add("\t\t" + targetName + " target = new " + targetName + "();");
        copy("this", lists, "target");
        lists.add("\t\t\t return target;");
        lists.add("\t\t}");

        return lists;
    }

    private List<String> chooseCopyPropertiesOther(String targetName) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t public " + targetName + " copyDTO(String ...preperties) {");
        lists.add("\t\t" + targetName + " target = new " + targetName + "();");
        CopyProperties("this", lists);
        lists.add("\t\t\t return target;");
        lists.add("\t\t}");

        return lists;
    }

    private List<String> chooseCopy(String sourceName) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t public void copy(" + entityName + " target) {");
        copy(sourceName, lists, "target");
        lists.add("\t }");
        return lists;
    }

    private void copy(String sourceName, List<String> lists, String target) {
        setMethodNameMap.forEach((key, value) -> {
            String getMethodName = getMethodNameMap.get(key);
//			lists.add("\t\t if(null != "+sourceName+"."+getMethodName+"()){");
            lists.add("\t\t\t " + target + "." + value + "(" + sourceName + "." + getMethodName + "());");
//			lists.add("\t\t }");
        });
    }

    private List<String> chooseCopyProperties(String sourceName) {
        List<String> lists = new ArrayList<String>();
        lists.add("\t/**");
        lists.add("\t  @param preperties需要copy的字段集合");
        lists.add("\t */");
        lists.add("\t public void copyPreperties(" + entityName + " target,String ...preperties) {");
        lists.add("\t\t if(ArrayUtils.isEmpty(preperties)){");
        lists.add("\t\t\t return;");
        lists.add("\t\t }");

        CopyProperties(sourceName, lists);
        lists.add("}");
        return lists;
    }

    private void CopyProperties(String sourceName, List<String> lists) {
        lists.add("\t\t for(String str : preperties){");
        fileds.forEach((filed) -> {
            String getName = getMethodNameMap.get(filed);
            String setName = setMethodNameMap.get(filed);
            lists.add("\t\t\t if(\"" + filed + "\".equals(str)){");
            lists.add("\t\t\t\t target." + setName + "(" + sourceName + "." + getName + "());");
            lists.add("\t\t\t\t continue;");
            lists.add("\t\t\t}");
        });
        lists.add("\t\t}");
    }

    private List<String> chooseToString(boolean isPage) {
        List<String> lists = new ArrayList<String>();
//        lists.add("\t private void combinationCharacter(String filed, Object value, StringBuilder build) {");
//        lists.add("\t\t if (!build.toString().equals(\"{\")) {");
//        lists.add("\t\t\t build.append(\",\");");
//        lists.add("\t\t }");
//        lists.add("\t\t build.append(\"\\\"\");");
//        lists.add("\t\t build.append(filed);");
//        lists.add("\t\t build.append(\"\\\":\\\"\");");
//        lists.add("\t\t build.append(value);");
//        lists.add("\t\t build.append(\"\\\"\");");
//        lists.add("}");

//		lists.add("\t private void chooseToStringOfDate(String filed, java.util.Date date, StringBuilder build) {");
//		lists.add("\t\t if(null != date) {");
//		lists.add("\t\t\t chooseTOString(filed,  date.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")), build);");
//		lists.add("\t\t }");
//		lists.add("\t }");

//        lists.add("\t private void chooseTOString(String filed, Object value, StringBuilder build) {");
//        lists.add("\t\t if (null != value) {");
//        lists.add("\t\t\t combinationCharacter(filed, value, build);");
//        lists.add("\t\t}");
//        lists.add("\t}");

//        lists.add("\t @Override");
//        lists.add("\t  public String toString() {");
//        lists.add("\t\t StringBuilder build = new StringBuilder();");
//        lists.add("\t\t build.append(\"{\");");
//        fileds.forEach((filed) -> {
//            String type = filedType.get(filed);
//            String getMethodName = getMethodNameMap.get(filed);
//
////			lists.add("\t\t if(null != "+getMethodName+"()){");
////			lists.add("\t\t\t if(build.toString().equals(\"{\")){");
////			lists.add("\t\t\t\t build.append(\"\\\""+filed+"\\\":\");");
////			lists.add("\t\t\t}else{");
////			lists.add("\t\t\t\t build.append(\",\\\""+filed+"\\\":\");");
////			lists.add("\t\t\t}");
//            if (type.equals("java.time.LocalDateTime")) {
//
//                lists.add("\t\t if(java.util.Objects.nonNull(" + getMethodName + "())){");
//                lists.add("\t\t\t chooseTOString(\"" + filed + "\", " + getMethodName + "().format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")), build);");
//                lists.add("\t\t}");
////				lists.add("\t\t\t build.append(\"\\\"\");");
////				lists.add("\t\t\t build.append(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format("+getMethodName+"()));");
////				lists.add("\t\t\t build.append(\"\\\"\");");
//            } else {
//                lists.add("\t\t chooseTOString(\"" + filed + "\", " + getMethodName + "(), build);");
////                lists.add("\t\t}");
////				lists.add("\t\t\t build.append(\"\\\"\");");
////				lists.add("\t\t\t build.append("+getMethodName+"());");
////				lists.add("\t\t\t build.append(\"\\\"\");");
//            }
////			lists.add("\t\t}");
//        });
//        if (isPage) {
//            lists.add("\t\t chooseTOString(\"page\", getPage(), build);");
//            lists.add("\t\t chooseTOString(\"row\", getRows(), build);");
//        }
//        lists.add("\t build.append(\"}\");");
//        lists.add("\t return build.toString();");
//        lists.add("\t}");
//        lists.add("}");
        return lists;
    }

    private String getJavaType(String type) {
        if (contains(dateType, type)) {
            if (Objects.equals("1", entity.getIsDateType())) {
                return "java.util.Date";
            }
            return "java.time.LocalDateTime";
        } else if (contains(intType, type)) {
            return "java.lang.Integer";
        } else if (contains(booleanType, type)) {
            statucFlag = Boolean.TRUE;
            return "java.lang.Boolean";
        } else if (contains(LongType, type)) {
            return "java.lang.Long";
        } else if (contains(bigdecType, type)) {
            return "java.math.BigDecimal";
        } else if (contains(LocalDateType, type)) {
            return "java.time.LocalDate";
        } else {
            return "java.lang.String";
        }
    }

    private boolean contains(String[] array, String character) {
        if (ArrayUtils.isEmpty(array) || StringUtils.isEmpty(character)) {
            return Boolean.FALSE;
        }

        for (String str : array) {
            if (Objects.nonNull(str) && Objects.equals(character.toLowerCase(), str.toLowerCase())) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    private String getDBType(String type) {
        if (type.toLowerCase().equals("int")) {
            return JDBCType.INTEGER.name();
        } else if (type.toLowerCase().equals("datetime")) {
            return JDBCType.DATE.name();
        } else if (type.toLowerCase().equals("text")) {
            return JDBCType.LONGVARCHAR.name();
        }
        return type.toUpperCase();
    }

    private String getFiled(String column) {
        String[] strs = column.split("_");
        StringBuilder build = new StringBuilder();

        for (int i = 0; i < strs.length; i++) {
            if (i == 0) {
                build.append(strs[i].substring(0, 1).toLowerCase());
            } else {
                build.append(strs[i].substring(0, 1).toUpperCase());
            }

            if (strs[i].length() > 1) {
                build.append(StringUtils.substring(strs[i], 1).toLowerCase());
            }
        }
        return build.toString();
    }

    private Integer getLength(String val1, String val2, String val3) {
        if (StringUtils.isNotEmpty(val1)) {
            BigDecimal bigDecimal = new BigDecimal(val1);
            return bigDecimal.longValue() > Integer.MAX_VALUE ? null : bigDecimal.intValue();
        }

        Integer val = 0;
        if (StringUtils.isNotEmpty(val2)) {
            val = val + Integer.valueOf(val2);
        }

        if (StringUtils.isNotEmpty(val3)) {
            val = val + Integer.valueOf(val3) + 1;
        }

        if (Objects.equals(val, 0)) {
            return null;
        }

        return val;
    }

    private String format(String character, String beforeCharacter, String startCharacter) {
        if (StringUtils.isNotEmpty(beforeCharacter)) {
            character = character.replace(beforeCharacter, "");
        }

        if (StringUtils.isNotEmpty(startCharacter)) {
            character = startCharacter + "_" + character;
        }

        String[] strs = character.split("_");
        StringBuilder build = new StringBuilder();

        for (String str : strs) {
            build.append(StringUtils.substring(str, 0, 1).toUpperCase());

            if (StringUtils.length(str) > 1) {
                build.append(StringUtils.substring(str, 1).toLowerCase());
            }
        }
        return build.toString();
    }

    private List<Map<String, String>> getColumnsData(String table, String dbName, String ip, String user, String pwd) {
        String sql = "select column_name,data_type,Character_maximum_length,numeric_precision,column_comment,numeric_scale from information_schema.columns where table_schema = '"
                + dbName + "'  and table_name = '" + table + "'  ORDER BY ordinal_position";
        return ConnectionUtil.select(sql, ip, user, pwd);
    }

    private String getPrimaryKeyColumns(String table, String dbName, String ip, String user, String pwd) {
        String sql = "SELECT c.COLUMN_NAME FROM  INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t, information_schema.TABLES AS ts, information_schema.KEY_COLUMN_USAGE AS c where  t.TABLE_NAME = ts.TABLE_NAME  AND ts.TABLE_NAME  = c.TABLE_NAME AND t.TABLE_SCHEMA = '"
                + dbName + "'  AND t.CONSTRAINT_TYPE = 'PRIMARY KEY'  and t.TABLE_NAME= '" + table + "'";
        List<Map<String, String>> lists = ConnectionUtil.select(sql, ip, user, pwd);

        return ((null == lists || lists.size() == 0)) ? null : lists.get(0).get("COLUMN_NAME");

    }

    public List<Map<String, String>> getTables(String database, String ip, String user, String pwd) {
        String sql = "select table_name from information_schema.tables where table_schema='" + database + "'";
        List<Map<String, String>> lists = ConnectionUtil.select(sql, ip, user, pwd);

        return ConnectionUtil.select(sql, ip, user, pwd);
    }

    private void write(List<String> lines, String path, String fileName) throws IOException {
        File file = new File(path + "/" + fileName);
        StringBuilder build = new StringBuilder();
        lines.forEach((line) -> {
            build.append(line);
            build.append("\r\n");
        });

        FileUtils.write(file, build.toString(), "UTF-8");
        System.out.println(file.getAbsolutePath());
    }

    private String formatFiledClass(String str) {
        return str.substring(0, 1).toLowerCase() + StringUtils.substring(str, 1);
    }

    private void chooseFeign(String path, String packageStr, String className, String feignService, String tableName) throws IOException {
        if (StringUtils.isNotEmpty(packageStr)) {
            List<String> lists = new ArrayList<String>();


            feignApi = className + "FeignApi";
            String url = StringUtils.replace(StringUtils.replace(tableName, "_", "/"), "-", "/").toLowerCase();
            lists.add("package " + packageStr + ";");
            String resultClass = "";
            if (StringUtils.isNotEmpty(responseDataImpl)) {
                lists.add("import " + responseDataImpl + ";");
                resultClass = StringUtils.substringAfterLast(responseDataImpl, ".");
            }

            lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + addDTO + ";");
            lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + updateDTO + ";");
            if (statucFlag) {
                lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + updateStatusDTO + ";");
            }
            lists.add("import " + getPackageStr(entity.getDtoStr()) + "." + queryDTO + ";");
            lists.add("import " + voImpl + ";");

//            lists.add("import io.swagger.annotations.ApiOperation;");
            lists.add("import org.springframework.cloud.openfeign.FeignClient;");
            lists.add("import org.springframework.web.bind.annotation.*;");
//            lists.add("import java.util.List;");
            lists.add("import com.baomidou.mybatisplus.core.metadata.IPage;");


            lists.add("@FeignClient(name = \"" + feignService + "\",path=\"" + url + "\")");
            lists.add("public interface " + feignApi + " {");
            lists.add("/**  分页查询       */");
            lists.add("\t @GetMapping(value = \"/list/limit/{page}/{pageLimit}\")");
            lists.add("\t " + resultClass + "<IPage<" + voName + ">> listLimit(@RequestBody " + queryDTO + " request,@PathVariable(\"page\") Integer page,@PathVariable(\"pageLimit\") Integer pageLimit) ;");

            String idType = filedType.get(idFiled);
            lists.add("/**  查询        详情*/");
            lists.add(" @GetMapping(value = \"view/{id}\")");
            lists.add("\t  " + resultClass + "<" + voName + "> view( @PathVariable(\"" + idFiled + "\") " + idType + " " + idFiled + ");");

            lists.add("\t/**新增*/");
            lists.add(" @PostMapping(value=\"/add\")");
            lists.add("\t " + resultClass + "<Object> add(@RequestBody " + addDTO + " request);");

            lists.add("\t /**修改*/");
            lists.add("  @PutMapping(value=\"/update\")");
            lists.add("\t " + resultClass + "<Object> update(@RequestBody " + updateDTO + " request);");
            if (statucFlag) {
                lists.add("\t// /**修改状态*/");
                lists.add(" //@DeleteMapping(value=\"/update/status\")");
                lists.add("\t// " + resultClass + "<Object> updateState(@RequestBody " + updateStatusDTO + " request);");
            }

//            lists.add("\t/**删除*/");
//            lists.add(" @GetMapping(value = \"view/{id}\")");
//            lists.add("\t BaseResult deleteById(List<Long> ids);");

            lists.add("}");
            write(lists, path, feignApi + ".java");
        }

    }

    private void chooseOperator() {
        fileds.add("operator");
        filedComment.put("operator", "操作人员");
        filedType.put("operator", "java.lang.String");
        getMethodNameMap.put("operator", "getOperator");
        setMethodNameMap.put("operator", "setOperator");
    }

    private boolean switchDTO(String key) {
        return (Objects.nonNull(entity.getDtoIng()) && StringUtils.indexOf(entity.getDtoIng(), key + ",") > 0);
    }
}
